Laravel 5.1 use limit in with() method of eloquent

怎甘沉沦 提交于 2019-12-23 18:55:03

问题


Eloquent

$staffGroup = StaffGroup::where('id', $id)
            ->with('staffGroupRight')
            ->first();

In StaffGroup Model:

public function staffGroupRight() {
    return $this->hasMany('Modules\Staff\Http\Models\StaffGroupRight');
}

what i have does is,

public function staffGroupRight() {
    return $this->hasMany('Modules\Staff\Http\Models\StaffGroupRight')->take(5);
}

but it gives total 5 rows for all staff_group but i want it to limit for one staff_group

For example

There are 10 staff_group then it gives 5 records of staffgrouprights for that 10 staff_group but i want it 5 for single staff_group

here with staffGroupRight return data appropriate to id of staff group.

but i want to set limit in that with() method data.

is it possible to set limit in with() method or not...??


回答1:


$staffGroup = StaffGroup::where('id', $id)
        ->with(['staffGroupRight' => function($query){
            return $query->take(10);
            }])
        ->first();

I assume you want to take 10 record of staffGroupRight.



来源:https://stackoverflow.com/questions/34082082/laravel-5-1-use-limit-in-with-method-of-eloquent

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