Using a Laravel model method in an Eloquent query

天大地大妈咪最大 提交于 2019-12-22 07:09:02

问题


This is for Laravel 5.2. I have a method defined as follows in my Users model:

public function name()
{
    return "$this->name_first $this->name_last";
}

I'm trying to figure out how to use that as part of a query, but it seems like it isn't possible for a somewhat obvious reason: the database doesn't know anything about the method and that makes perfect sense. However, the concept of what I'm trying to achieve makes sense in certain contexts, so I'm trying to see if there's a way to accomplish it naturally in Eloquent.

This doesn't work, but it represents what I'm trying to accomplish:

public function index(Request $request)
{
    $query = new User();

    if(Request::has('name')) {
        $query = $query->where('name', 'LIKE', '%' . Request::input('name') . '%');
    }

    return $query->get();
}

In short, the database only knows about name_first and name_last, but I'd like to be able to search (and sort) on name without storing it. Maybe storing the concatenated name is no big deal and I should just do it, but I'm also trying to learn.


回答1:


I agree with Bogdan, The issue of having spaces either in the first or the last name makes querying on the individual columns difficult, so this is probably the way to go. Code reuse can be increased by defining it as a custom scope: https://laravel.com/docs/5.2/eloquent#local-scopes

// class User
public function scopeOfFullNameLike($query, $fullName)
{
    return $query->whereRaw('CONCAT(name_first, " ", name_last) LIKE "%?%"', [$fullName]);
}
// ...
User::ofFullNameLike('john doe')->get();



回答2:


That would mean you should be concatenating the column value at the database level. Which means you could use CONCAT and a whereRaw clause:

$query->whereRaw('CONCAT(name_first, " ", name_last) LIKE ?', ['%' . Request::input('name') . '%']);

Or as an alternative if you want the full name to be selected as part of the result, you could concatenate within the select and use having instead of where to be able to use a column alias:

$query->select('*', DB::raw('CONCAT(name_first, " ", name_last) as name'))
      ->having('name', 'LIKE', '%' . Request::input('name') . '%');

Not the most compact solutions, but things involving MySQL functions need some raw SQL to work with the Query Builder.



来源:https://stackoverflow.com/questions/35856456/using-a-laravel-model-method-in-an-eloquent-query

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