Returning missing results from many to many table

我的未来我决定 提交于 2019-12-24 08:09:18

问题


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 have corresponding record in BrandUser table...

I have tried the following query:

public function getUserBrands($userId) {
        $select = new Select();
        $select->from(array('bu' => $this->table));
        $select->join(array('b' => 'brands'), 'bu.brandId = b.id', array('id','name'));
        $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();
    }

But I only get users which HAVE corresponding record in the BrandUser table... I need to get the rest of the brands which don't have the corresponding value in BrandUser... How can I do this??


回答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();
}


来源:https://stackoverflow.com/questions/37681800/returning-missing-results-from-many-to-many-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!