14

I have two tables, say "users" and "users_actions", where "users_actions" has an hasMany relation with users:

users

id | name | surname | email...

actions

id | id_action | id_user | log | created_at

Model Users.php

class Users {
    public function action()
    { 
       return $this->hasMany('Action', 'user_id')->orderBy('created_at', 'desc');
    }
}

Now, I want to retrieve a list of all users with their LAST action.

I saw that doing Users::with('action')->get(); can easily give me the last action by simply fetching only the first result of the relation:

foreach ($users as $user) {
   echo $user->action[0]->description;
}

but I wanted to avoid this of course, and just pick ONLY THE LAST action for EACH user.

I tried using a constraint, like

Users::with(['action' => function ($query) {
    $query->orderBy('created_at', 'desc')
          ->limit(1);
    }])
->get();

but that gives me an incorrect result since Laravel executes this query:

SELECT * FROM users_actions WHERE user_id IN (1,2,3,4,5)
ORDER BY created_at
LIMIT 1

which is of course wrong. Is there any possibility to get this without executing a query for each record using Eloquent? Am I making some obvious mistake I'm not seeing? I'm quite new to using Eloquent and sometimes relationship troubles me.

Edit:

A part from the representational purpose, I also need this feature for searching inside a relation, say for example I want to search users where LAST ACTION = 'something'

I tried using

$actions->whereHas('action', function($query) {
    $query->where('id_action', 1);
});

but this gives me ALL the users which had had an action = 1, and since it's a log everyone passed that step.


Edit 2:

Thanks to @berkayk looks like I solved the first part of my problem, but still I can't search within the relation.

Actions::whereHas('latestAction', function($query) {
    $query->where('id_action', 1);
});

still doesn't perform the right query, it generates something like:

select * from `users` where 
 (select count(*) 
   from `users_action` 
   where `users_action`.`user_id` = `users`.`id` 
   and `id_action` in ('1')
  ) >= 1 
order by `created_at` desc

I need to get the record where the latest action is 1

miken32
  • 42,008
  • 16
  • 111
  • 154
Damien Pirsy
  • 25,319
  • 8
  • 70
  • 77
  • OMG! **too many edits**, for clean question and answer refer to: https://stackoverflow.com/q/53837614/8740349 – Top-Master Dec 07 '21 at 18:35

6 Answers6

17

I think the solution you are asking for is explained here http://softonsofa.com/tweaking-eloquent-relations-how-to-get-latest-related-model/

Define this relation in User model,

public function latestAction()
{
  return $this->hasOne('Action')->latest();
}

And get the results with

User::with('latestAction')->get();
berkayk
  • 2,376
  • 3
  • 21
  • 26
  • Awesome! +1 that solves just part of my problem though, how can I search inside this relation? Say, now I have the latest, how do I verify a latest record condition? (see "edit." part in my question) – Damien Pirsy Nov 18 '15 at 13:31
  • Try this `Users::with(['latestAction' => function ($query) { $query->where('id_action', 1); }])` – Pawel Bieszczad Nov 18 '15 at 16:36
16

I created a package for this: https://github.com/staudenmeir/eloquent-eager-limit

Use the HasEagerLimit trait in both the parent and the related model.

class User extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

class Action extends Model {
    use \Staudenmeir\EloquentEagerLimit\HasEagerLimit;
}

Then simply chain ->limit(1) call in your eager-load query (which seems you already do), and you will get the latest action per user.

Top-Master
  • 7,611
  • 5
  • 39
  • 71
Jonas Staudenmeir
  • 24,815
  • 6
  • 63
  • 109
14

My solution linked by @berbayk is cool if you want to easily get latest hasMany related model.

However, it couldn't solve the other part of what you're asking for, since querying this relation with where clause would result in pretty much the same what you already experienced - all rows would be returned, only latest wouldn't be latest in fact (but latest matching the where constraint).

So here you go:

the easy way - get all and filter collection:

User::has('actions')->with('latestAction')->get()->filter(function ($user) {
   return $user->latestAction->id_action == 1;
});

or the hard way - do it in sql (assuming MySQL):

User::whereHas('actions', function ($q) { 

  // where id = (..subquery..)
  $q->where('id', function ($q) { 

    $q->from('actions as sub')
      ->selectRaw('max(id)')
      ->whereRaw('actions.user_id = sub.user_id');

  })->where('id_action', 1);

})->with('latestAction')->get();

Choose one of these solutions by comparing performance - the first will return all rows and filter possibly big collection.

The latter will run subquery (whereHas) with nested subquery (where('id', function () {..}), so both ways might be potentially slow on big table.

Jarek Tkaczyk
  • 78,987
  • 25
  • 159
  • 157
  • Wonderful! I ended up using your second suggestion, since I'm paginating the results and the first - apart from being potentially too big - won't work properly when paginating. I tweaked a bit the query to match my current implementation (have to use an IN() clause), but you put me on the right path. Thanks a lot! – Damien Pirsy Nov 19 '15 at 09:12
  • Gotta wait 2 more hours before awarding the bounty, brb – Damien Pirsy Nov 19 '15 at 09:14
1

Let change a bit the @berkayk's code.

Define this relation in Users model,

public function latestAction()
{
    return $this->hasOne('Action')->latest();
}

And

Users::with(['latestAction' => function ($query) {
    $query->where('id_action', 1);
}])->get();
Pantelis Peslis
  • 14,930
  • 5
  • 44
  • 45
1

To load latest related data for each user you could get it using self join approach on actions table something like

select u.*, a.*
from users u
join actions a on u.id = a.user_id
left join actions a1 on a.user_id = a1.user_id
and a.created_at < a1.created_at
where a1.user_id is null
a.id_action = 1 // id_action filter on related latest record

To do it via query builder way you can write it as

DB::table('users as u')
  ->select('u.*', 'a.*')
  ->join('actions as a', 'u.id', '=', 'a.user_id')
  ->leftJoin('actions as a1', function ($join) {
        $join->on('a.user_id', '=', 'a1.user_id')
             ->whereRaw(DB::raw('a.created_at < a1.created_at'));
   })
  ->whereNull('a1.user_id')
  ->where('aid_action', 1) // id_action filter on related latest record
  ->get();

To eager to the latest relation for a user you can define it as a hasOne relation on your model like

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class User extends Model
{
    public function latest_action()
    {
        return $this->hasOne(\App\Models\Action::class, 'user_id')
            ->leftJoin('actions as a1', function ($join) {
                $join->on('actions.user_id', '=', 'a1.user_id')
                    ->whereRaw(DB::raw('actions.created_at < a1.created_at'));
            })->whereNull('a1.user_id')
            ->select('actions.*');
    }
}

There is no need for dependent sub query just apply regular filter inside whereHas

User::with('latest_action')
    ->whereHas('latest_action', function ($query) { 
      $query->where('id_action', 1);
    })
    ->get();
M Khalid Junaid
  • 63,861
  • 10
  • 90
  • 118
-3

Laravel Uses take() function not Limit

Try the below Code i hope it's working fine for u

Users::with(['action' => function ($query) {
      $query->orderBy('created_at', 'desc')->take(1);
}])->get(); 

or simply add a take method to your relationship like below

 return $this->hasMany('Action', 'user_id')->orderBy('created_at', 'desc')->take(1);
Shahid Ahmad
  • 764
  • 1
  • 7
  • 15