Okay after hours of research and still using DB::select I have to ask this question. Because I am about to throw 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
DB::table('users')
->select('first_name', 'TotalCatches.*')
->join(DB::raw('(SELECT user_id, COUNT(user_id) TotalCatch,
DATEDIFF(NOW(), MIN(created_at)) Days,
COUNT(user_id)/DATEDIFF(NOW(), MIN(created_at))
CatchesPerDay FROM `catch-text` GROUP BY user_id)
TotalCatches'),
function($join)
{
$join->on('users.id', '=', 'TotalCatches.user_id');
})
->orderBy('TotalCatches.CatchesPerDay', 'DESC')
->get();