Yii2在join语句中有很多条件

时间:2014-08-31 21:45:33

标签: join conditional-statements yii2

我需要在JOIN语句中定义更多条件。 如何在具有hasMany关系的Yii2中进行此操作?:

... LEFT JOIN命令ON(customer.id = order.customer_id AND orders.position = 1)...

我有一个GridView的DataProvider。它看起来像这样:

...
public function search($params)
{
    $query = Customer::find()
        ->joinWith('orders');

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

型号:

...
public function getFirstOrder()
{
    $query = $this->hasMany(Orders::className(), ['customer_id' => 'id']);
    return $query;
}
...

甚至可能吗?

1 个答案:

答案 0 :(得分:2)

public function search($params){


    $activeDataProvider = new ActiveDataProvider([
                                        "query" => Customer::find()
                                                   ->joinWith('orders')
                              ]);

    // Valdate the search $params.

    // Build your query depending on search params. I am assuming we get key => value pair in params

     foreach($params as $key => $value){

      $activeDataProvider->query->andWhere("`$key`  = '$value'");           

     }

     return $activeDataProvider;

}

我希望能帮到你:)。

您还可以使用以下方式预览生成的SQL:

    $command = $activeDataProvider->query->createCommand();
    print_r ($command->sql);