如何使用Laravel Eloquent根据属性/访问者条件查询对象?

时间:2022-10-15 22:48:00

Working with the examples from the documentation, if I have a accessor attribute like this:

使用文档中的示例,如果我有这样的访问者属性:

public function getFullNameAttribute()
{
    return "{$this->first_name} {$this->last_name}"; // both are real columns
}

How can I run a where based on a computed value? Something like:

如何根据计算值运行where?就像是:

$user = User::where('full_name', 'John Doe');

It should match items where first_name is John and last_name is Doe.

它应匹配first_name为John且last_name为Doe的项目。

Is there a way to do this or am I doing it wrong?

有办法做到这一点还是我做错了?

Update: I found a similar question asked for Laravel 4 and it has an answer, however it states that the filtering is applied after the query is made, which will be very inefficient. Has there been any update to this mechanism since Laravel 5?

更新:我发现一个类似的问题要求Laravel 4并且它有一个答案,但是它声明在进行查询后应用过滤,这将是非常低效的。自Laravel 5以来,这个机制有没有更新?

2 个解决方案

#1


1  

You can use raw where statement with CONCAT mysql function:

你可以使用带有CONCAT mysql函数的raw where语句:

->whereRaw('CONCAT(first_name," ",last_name) = "John Doe"')

Or just with 2 wheres:

或者只是2轮:

->where('first_name','John')->where('last_name','Doe')

#2


1  

Rafal Migda's answer is probably the most correct, but I figured out a more elegant--or should I say, Eloquent--way of doing what I wanted, utilising scopes. In my model, I put:

Rafal Migda的回答可能是最正确的,但我想出了一个更优雅的 - 或者我应该说,Eloquent - 利用范围做我想要的方式。在我的模型中,我把:

public function scopeFullName($query, $fullName)
{
    return $query->whereRaw('CONCAT(first_name, " ", last_name) = "' . $fullName . '"');
}

This will allow me to use the query scope like this:

这将允许我使用这样的查询范围:

$user = User::fullName('John Doe');

#1


1  

You can use raw where statement with CONCAT mysql function:

你可以使用带有CONCAT mysql函数的raw where语句:

->whereRaw('CONCAT(first_name," ",last_name) = "John Doe"')

Or just with 2 wheres:

或者只是2轮:

->where('first_name','John')->where('last_name','Doe')

#2


1  

Rafal Migda's answer is probably the most correct, but I figured out a more elegant--or should I say, Eloquent--way of doing what I wanted, utilising scopes. In my model, I put:

Rafal Migda的回答可能是最正确的,但我想出了一个更优雅的 - 或者我应该说,Eloquent - 利用范围做我想要的方式。在我的模型中,我把:

public function scopeFullName($query, $fullName)
{
    return $query->whereRaw('CONCAT(first_name, " ", last_name) = "' . $fullName . '"');
}

This will allow me to use the query scope like this:

这将允许我使用这样的查询范围:

$user = User::fullName('John Doe');