For this issue, I have reduced the complexity of the database.
I have a table with Orders
id
name
And a table with Suborders
id
order_id
user_id
One order may contain numerous suborders. A suborder is only connected to one order.
The suborders are stored in order of entry. Increasing id. I want to get the list of
the orders for which user_id=123 is the last one who add a suborder.
$myuserid=123;
orders = Order::
whereHas('suborders', function ($query) use ($myuserid) {
$query->where('user_id', '=', $myuserid)
->take(1)
->latest()
->get();
})->get();
I was hoping that the code above would only return a line when the last user_id = 123.
But it gives the last line for which user_id=123 is the handler. So rows added after
my line are ignored.
I think that I first have to get the last line and after that check if it is 123,
but I’m stuck in the syntax. In unknown column user_id errors.
asking it correcty]
2
Answers
To achieve your goal of retrieving orders for which
user_id=123
is the last one who added a suborder, you can modify your query to first get the latest suborder added byuser_id=123
, and then retrieve the corresponding order. Here’s how you can do it:This code first retrieves the latest suborder added by
user_id=123
. Then, it retrieves the corresponding order using the relationship between orders and suborders. If no suborder is found foruser_id=123
, you can handle that case accordingly.first of all you need to define this last suborder relation. Each order has many sub orders (via
order_id
insub_orders
table), but each order also belongs to only one last sub order (vialast_suborder_id
inorders
table ?!?!?).To create this relation we need this field. How you calculate this
last_suborder_id
is up to you. You may want to "cache it" on the table each time a sub order is created or calculate in on the fly:With this in place we can: