2017-08-27 109 views
2

我想從主表中的所有數據Yii2獲取數據左連接關係與自身的條件與連接表

MainTableSearch.php

class MainTableSearch extends MainTable 
{ 
    public $table_two; 
    public $table_three 

    public function search($params) 
    { 
     $query = MainTable::find(); 

     $query->joinWith(['table_two']); 
     $query->joinWith(['table_three']); 

     $dataProvider = new ActiveDataProvider([ 
      'query' => $query, 
     ]); 
.... 

MainTable.php

class MainTable extends \yii\db\ActiveRecord 
{ 
    public static function tableName() 
    { 
     return 'main_table'; 
    } 

    public function getTableTwo() 
    { 
     return $this->hasOne(TableTwo::className(), [main_id' => 'id'])->andWhere(['table_two.something' => 2]); 
    } 

    public function getTableThree() 
    { 
     return $this->hasOne(TableThree::className(), ['main_id' => 'id'])->andWhere(['table_three.something' => 2]); 
    } 

我想在網格視圖中查看主表中的所有數據,如果table_two.something或table_three.s沒有滿足在該領域返回null的要求。

我也試過

return $this->hasOne(TableThree::className(), ['main_id' => 'id'])->andWhere(['table_three.something' => 2])->orWhere(['table_three.something' => NULL]); 
+0

您在使用搜索功能時有錯誤? – scaisEdge

+0

不,來自主表的某些數據與table_two或table_three沒有相關性,並且該數據不顯示在網格視圖中我想查看它們 – shilecro

回答

0

[解決]

$query->leftJoin('table_two','main_table.id = table_two.main_id 
AND (table_two.something=1 OR table_two.something IS NULL)'); 
+1

您不想使用「= NULL」,這總是錯誤的數據庫(與編程語言相反)。你想要「IS NULL」。 –

+0

@AdrianSmith男人在活着的時候學習:) – shilecro