I'm having a problem building a query with Yii2.
Let's say we have four related models: Customer, Order, Orderitem and Orderitempicture.
Order is related to Customer, Orderitem is related to Order, and Orderitempicture is related to Orderitem.
Below is the code:
Customers::find()
->where(['id' => $id])
->with(['orders' => function($q) {
$q->select(['id', 'name', 'customer_id', '(select COUNT(*) from orders where customer_id=order.id) AS thecount'])->having('thecount > 0');
}])
->with(['orders.orderitems' => function($q) {
$q->select(['id', 'name', 'price', 'order_id']);
}])
->with(['orders.orderitems.orderitemspictures' => function($q) {
$q->select(['id', 'src_thumb', 'orderitem_id'])->orderBy("id desc")->limit(1);
}])
->select(['id'])
->asArray()
->one();
This is one of the executed statements from the debugger:
SELECT `id`, `src_thumb`, `orderitem_id` FROM `orderitempicture` WHERE `order_id` IN ('37', '42', '29', '36', '39', '41', '30', '40', '28', '38') ORDER BY `id` DESC LIMIT 1
Now my problem is in this this line:
$q->select(['id', 'src_thumb', 'orderitem_id'])->orderBy("id desc")->limit(1);
What I am trying to do get one orderitempicture for each orderitem, however, what happens is that the SQL to get orderitempictures is merged into one statement, and the limit is applied to that statement, so the result is that I only get ONE orderitempicture for one orderitem, and I get nothing for the rest.
How can I set a limit to get one child for each parent? Is there a way to tell Yii to create multiple queries for each record in the parent and set a limit on that instead of creating one query?