Reputation: 63
I need to define more conditions in the JOIN statement. How can I make this in Yii2 with a hasMany relation?:
... LEFT JOIN orders ON (customer.id = order.customer_id AND orders.position = 1) ...
I have a DataProvider for GridView. It look like this:
...
public function search($params)
{
$query = Customer::find()
->joinWith('orders');
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
return $dataProvider;
}
...
Model:
...
public function getFirstOrder()
{
$query = $this->hasMany(Orders::className(), ['customer_id' => 'id']);
return $query;
}
...
Is it even possible?
Upvotes: 2
Views: 6462
Reputation: 529
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;
}
I hope that helps you :)
You can also preview the generated sql using:
$command = $activeDataProvider->query->createCommand();
print_r ($command->sql);
Upvotes: 2