'Where like' clause using the concatenated value of 2 columns with eloquent

不打扰是莪最后的温柔 提交于 2020-01-01 12:30:37

问题


I have a query that searches for a term in several columns and one of them has to be a full name.

I have separated the full name in name and lastname, so I have to concat these 2 values when searching.

I have this right now only searching for name. How I would add the concat to lastname? I was investigating over mutators but I don't know if it is the way to way.

public function search($searchQuery)
{
    $search = "%{$searchQuery}%";

    return Order::with('customer')
                    ->orWhereHas('customer', function($query) use ($search){
                        $query->where('dni', 'like', $search);
                    })
                    ->orWhereHas('customer', function($query) use ($search){
                        $query->where('name', 'like', $search);
                    })
                    ->orWhere('code', 'like', $search)
                    ->paginate(15);
}

回答1:


Mutators are not the way to go here, because they do not affect the query you're building, they are only used on the values stored in the model. However you can use the following condition:

$query->where(DB::raw('CONCAT_WS(" ", name, lastname)'), 'like', $search);

The MySQL function CONCAT_WS will concatenate two strings, gluing them with the string passed as the first parameter. So in this case if the first name is John and the last name is Smith, the condition will be evaluated to this "John Smith" like "%query%". The DB:raw is used to avoid the first part of the condition to be escaped which would put backticks around the concatenation statement.



来源:https://stackoverflow.com/questions/33896662/where-like-clause-using-the-concatenated-value-of-2-columns-with-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!