Laravel 5 eager loading with limit

谁都会走 提交于 2019-11-30 13:51:59

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.

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();

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 you can apply ->limit(1) to your relationship and you will get the latest action per user.

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();

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();

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!