Laravel:如何在收集前在自定义 GetAttribute 中进行过滤

将Custom Get Attribute字段检索到collection. 我现在需要在使用前过滤get()


例子:


对于is_paid自定义属性


//is_paid

public function getIsPurchasedAttribute()

{

    //Since purchased has one relation with user

    return !empty($this->purchasedRelation) ? true : false;

}

我现在需要User基于 is_purchased 进行检索,例如:


public function index(Request $request){

        $isPaid = $request->is_paid;


        $users = User::query();


        if($isPaid){

            $users = $users->where('is_paid', true);


        }


        $users = $users->paginate(10);


        return view('user.index', [

            'users' => $users

        ]);


    }

如果我这样做,它将返回:


未找到列:1054 'where 子句中的未知列'is_paid'


是的,我可以这样做,但我现在无法使用paginate功能:


$users = User::get();


$users = $users->where('is_paid', 1);


return view('user.index', [

    'users' => $users

]);


慕森王
浏览 87回答 2
2回答

喵喔喔

whereHas()您可以使用该方法返回所有已购买的用户。public function index(Request $request){    $users = User::query();    if ($request->is_paid) {        $users->whereHas('purchasedRelation');    }    return view('user.index', [        'users' => $users->paginate(10),    ]);}

倚天杖

如果有人偶然发现同样的错误并供将来参考,我将发布我用来解决问题的方法:创建的自定义getAttribute 只能在检索模型后获取。那是使用first()或find()您不能在查询集合中进行过滤。所以为了过滤唯一的is_paid属性;我首先检索模型的集合,然后像这样过滤:public function index(Request $request){    $isPaid = $request->is_paid;    $users = User::get();    if($isPaid){        $users = $users->where('is_paid', true);    }    $users = $users->paginate(10);    return view('user.index', [        'users' => $users    ]);}为了使用分页进行收集,我遵循了Gist For Paginated Collections In Laravel
打开App,查看更多内容
随时随地看视频慕课网APP