【问题标题】:Adding a filter helper method to Laravel model向 Laravel 模型添加过滤器辅助方法
【发布时间】:2020-01-27 18:06:04
【问题描述】:

我想在我的 Laravel Product 模型中添加一个方法,该方法通过 name attr 过滤并返回所有匹配产品的集合,这就是我得到的:

产品.php

public function filterByName($query)
{
    return $this->where('name','LIKE','%'.$query.'%')->get();
}

ProductController.php

$products = collect(new Product);
$products->filterByName($name);

这个的正确用法是什么?我需要使用 QueryFilter 吗?

【问题讨论】:

    标签: php laravel eloquent laravel-5.8 eloquent-relationship


    【解决方案1】:

    您是在谈论范围吗?

    public function scopeByName($query, $param)
    {
        return $query->where('name','LIKE','%'.$param.'%');
    }
    

    然后

    $products = Product::byName('xyz')->get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-10
      • 1970-01-01
      • 2023-03-03
      • 2011-03-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多