laravel 雄辩的搜索/自定义属性的位置
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28020053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
eloquent search/where on custom attributes
提问by NiRR
I added a custom attribute to my model
我为我的模型添加了一个自定义属性
public function getTouchedAttribute() { ...
I would like to add this to a query
我想将此添加到查询中
hasMany()->where('touched', ...)
but obviously this isn't a column in the table.
但显然这不是表格中的一列。
what is the most elegant way to achieve this behavior?
实现这种行为的最优雅的方法是什么?
采纳答案by lukasgeiter
One option (and probably the better one in terms of performance) would be to mimic the attribute with raw SQL functions. (Can't help you with that because I don't know what touched
does)
一种选择(在性能方面可能是更好的选择)是使用原始 SQL 函数模拟属性。(无法帮助你,因为我不知道做什么touched
)
The other way is to use filter
on the resulting collection:
另一种方法是filter
在结果集合上使用:
$collection = Model::all();
$filtered = $collection->filter(function($model){
return $model->touched == true;
});
回答by U?ur Ar?c?
I know this is a 4 year old topic (from 2015) but it's still getting traffic from web searches. So I want to share an idea;
我知道这是一个 4 年前的话题(从 2015 年开始),但它仍然从网络搜索中获得流量。所以我想分享一个想法;
You can use Local Query Scopesof Eloquent to define custom where clauses.
您可以使用Eloquent 的本地查询范围来定义自定义 where 子句。
As said in documentation:
正如文档中所说:
Local scopes allow you to define common sets of constraints that you may easily re-use throughout your application. For example, you may need to frequently retrieve all users that are considered "popular". To define a scope, prefix an Eloquent model method with scope.
局部作用域允许您定义常见的约束集,您可以在整个应用程序中轻松地重用这些约束。例如,您可能需要经常检索所有被视为“受欢迎”的用户。要定义范围,请在 Eloquent 模型方法前加上范围。
And an example: If you define a custom scope on your model:
以及一个示例:如果您在模型上定义自定义范围:
public function scopePopular($query)
{
return $query->where('votes', '>', 100);
}
You can use it directly with your model.
您可以直接将它用于您的模型。
App\User::popular()->orderBy('created_at')->get();
So you can define a scopeTouched()
method and implement your logic.
I assume if updated_at not equal to created_at the row is touched here. Of course you can change this behaviour.
所以你可以定义一个scopeTouched()
方法并实现你的逻辑。我假设如果updated_at 不等于created_at,则此处触及该行。当然,您可以更改此行为。
public function scopeTouched($query)
{
return $query->where('updated_at', '!=', 'created_at');
}
And use it with your model.
并将其与您的模型一起使用。
Model::touched()->get();
And of course you can use it with other query builder methods.
当然,您可以将它与其他查询构建器方法一起使用。
Model::touched()->paginate(20);
Model::touched()->orderBy('id', 'DESC')->take(10)->get();
Model::touched()->latest()->first();