[英]Adding a filter helper method to Laravel model
I'd like to add a method to my Laravel Product
model which filters by name
attr and returns a collection of all matching products, here's what I've got:我想向我的 Laravel Product
model 添加一个方法,该方法按name
attr 过滤并返回所有匹配产品的集合,这就是我得到的:
public function filterByName($query)
{
return $this->where('name','LIKE','%'.$query.'%')->get();
}
$products = collect(new Product);
$products->filterByName($name);
What's the correct usage of this?这个的正确用法是什么? Do I need to use a QueryFilter?我需要使用 QueryFilter 吗?
Are you talking about scope?你说的是scope吗?
public function scopeByName($query, $param)
{
return $query->where('name','LIKE','%'.$param.'%');
}
and then接着
$products = Product::byName('xyz')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.