Okay after hours of research and still using DB::select I have to ask this question. Because I am about to trough my computer away ;).
I want to get the last input of a user (base on the timestamp). I can do this with the raw sql
SELECT c.*, p.*
FROM users c INNER JOIN
(
SELECT user_id,
MAX(created_at) MaxDate
FROM `catch-text`
GROUP BY user_id
) MaxDates ON c.id = MaxDates.user_id INNER JOIN
`catch-text` p ON MaxDates.user_id = p.user_id
AND MaxDates.MaxDate = p.created_at
I got this query from another post here on stackoverflow.
I have tried everything to do this with the fluent query builder in Laravel however with no success.
I know the manual says you can do this:
DB::table('users')
->join('contacts', function($join)
{
$join->on('users.id', '=', 'contacts.user_id')->orOn(...);
})
->get();
But that is not helping much because I do not see how I could use a subquery there? Anyone who can light up my day?
Ok for all of you out there that arrived here in desperation searching for the same problem. I hope you will find this quicker then I did ;O.
This is how it is solved. JoostK told me at github that "the first argument to join is the table (or data) you're joining.". And he was right.
Here is the code. Different table and names but you will get the idea right? It t
I think what you looking for is "joinSub". It's supported from laravel ^5.6. If you using laravel version below 5.6 you can also register it as macro in your app service provider file. like this https://github.com/teamtnt/laravel-scout-tntsearch-driver/issues/171#issuecomment-413062522
I was looking for a solution to quite a related problem: finding the newest records per group which is a specialization of a typical greatest-n-per-group with N = 1.
The solution involves the problem you are dealing with here (i.e., how to build the query in Eloquent) so I am posting it as it might be helpful for others. It demonstrates a cleaner way of sub-query construction using powerful Eloquent fluent interface with multiple join columns and
where
condition inside joined sub-select.In my example I want to fetch the newest DNS scan results (table
scan_dns
) per group identified bywatch_id
. I build the sub-query separately.The SQL I want Eloquent to generate:
I did it in the following way:
UPDATE:
Since Laravel 5.6.17 the sub-query joins were added so there is a native way to build the query.
Query with sub query in Laravel
I can't comment because my reputation is not high enough. @Franklin Rivero if you are using Laravel 5.2 you can set the bindings on the main query instead of the join using the setBindings method.
So the main query in @ph4r05's answer would look something like this: