[英]Returning missing results from many to many table
我有一個表結構如下:
Brands => BrandUser <= Users
我需要獲得BrandUser表中具有相應記錄的品牌以及BrandUser表中沒有相應記錄的品牌......
我嘗試了以下查詢:
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();
}
但我只獲得在BrandUser表中有相應記錄的用戶......我需要得到BrandUser中沒有相應價值的其他品牌......我怎么能這樣做?
請注意,我不熟悉Zend-Framework,因此您可能需要對此進行一些調整。 但是您需要使用Brands
作為主要/第一個表,以便它可以首先獲取該表的所有記錄,然后將其與其余表匹配。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.