Skip to content Skip to sidebar Skip to footer

Returning Missing Results From Many To Many Table

I have a table structure like following: Brands => BrandUser <= Users I need to get brands which have corresponding record in the BrandUser table and the ones which don't ha

Solution 1:

Mind you, I'm not familiar with Zend-Framework, so you may have to adapt this a bit. But you need to use Brands as the primary/first table, so that it can get all the records of that table first, then match it to the rest of the tables.

public function getUserBrands($userId) {
    $select = new Select();
    $select->from(array('b' => 'brands'));
    $select->join(array('bu' => $this->table), 'bu.brandId = b.id', array('id','name'),Select::JOIN_LEFT);
    $select->join(array('u' => 'users'), 'u.id = bu.userId', array('id','username'),Select::JOIN_LEFT);
    $where = new Where();
    $where->equalTo("bu.userId",$userId);
    $select->where($where);
    return $this->branduserTable->selectWith($select)->toArray();
}

Post a Comment for "Returning Missing Results From Many To Many Table"