Laravel 5 eager loading with limit

前端 未结 6 1187
小蘑菇
小蘑菇 2020-12-09 12:28

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

users

id | name          


        
6条回答
  •  借酒劲吻你
    2020-12-09 13:18

    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.

提交回复
热议问题