在雄辩查询中使用Laravel模型方法

在雄辩查询中使用Laravel模型方法

本文介绍了在雄辩查询中使用Laravel模型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是针对Laravel 5.2的。我的用户模型中有一个定义如下的方法:

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();
}

简而言之,数据库只知道 name_first name_last ,但我希望能够在名称上搜索(和排序)不存储。可能存储连接名称并不重要,我应该这样做,但我也想学习。

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.

推荐答案

我同意Bogdan,在第一个或最后一个名字上放置空格的问题使得对各个列的查询变得困难,所以这可能是要走的路。可以通过将其定义为自定义范围来增加代码重用:

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();

这篇关于在雄辩查询中使用Laravel模型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 16:42