【问题标题】:Laravel: How to Filter In Custom GetAttribute Before CollectionLaravel:如何在收集之前过滤自定义 GetAttribute
【发布时间】:2020-03-22 10:59:11
【问题描述】:

我可以在将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;
}

我现在需要根据 is_purchased 检索User,例如:

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

【问题讨论】:

    标签: php laravel laravel-5 eloquent


    【解决方案1】:

    您可以使用whereHas() 方法退回所有已购买的用户。

    public function index(Request $request){
        $users = User::query();
    
        if ($request->is_paid) {
            $users->whereHas('purchasedRelation');
        }
    
        return view('user.index', [
            'users' => $users->paginate(10),
        ]);
    }
    

    【讨论】:

    • 逻辑有点多。而且我不想复制代码。
    • 为什么你认为你会重复代码?它还有什么其他逻辑?
    【解决方案2】:

    如果有人偶然发现相同的错误并供将来参考,我将发布我用来解决问题的方法:

    创建的自定义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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2016-12-21
      • 2021-12-23
      • 2013-06-01
      相关资源
      最近更新 更多