Yii2使用连接表获取数据

时间:2017-08-27 17:07:31

标签: php mysql 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.something不符合在该字段中返回null的要求。

我也试过

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

1 个答案:

答案 0 :(得分:0)

[解决]

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