Reputation: 45
I have a table with products, and another table with movements of products (addition, substraction) and table of authors of these movements. I want to get all products with the last movement in Eloquent ORM I have tried...
$products = Product::with( array
(
'movs' => function ( $query )
{
$query->orderBy( 'id', 'dsc' )->with('author')->first();
}
) )->get();
But only get a zeroed movs array.
But when I do
$products = Product::with( array
(
'movs' => function ( $query )
{
$query->orderBy( 'id', 'dsc' )->with('author');
}
) )->get();
I get all the according related models (movs and authors)... Is there any way to get this in Eloquent or I have to do with query builder... if so... how?
Thanks you in advance.
Upvotes: 0
Views: 2508
Reputation: 377
You must create a new relationship that is hasOne instead of hasMany.
This is the solution: http://alexkaye.co.uk/2015/01/04/eloquent-get-first-last-related-row/
Upvotes: 1
Reputation: 45
Well... impossible to build with Eloquent... Impossible to build with query builder (error when using db raw) so... at the end build with mysql and DB::select
The sentence says select the products with last movement and author of the movement. (Null if not movements)
Relying in last movement on the last id not the date
$mq = "select *
from products
left join
(
select concat (users.first_name,' ', users.last_name) as author,
from users
join (
select *
from movs
join (
select max(movs.id) as id
from movs
group by product_id
) as movsids
on (movsids.id = movs.id)
)
as movuser
on movuser.author_id = users.id
)
as last_movs
on products.id = last_movs.product_id";
return DB::select($mq);
Upvotes: 0