Laravel 所有请求中的附加属性

Dmi*_*rev 6 oop model-view-controller laravel eloquent

再会。例如,我有一个People带有字段/属性的模型:

name
surname
Run Code Online (Sandbox Code Playgroud)

并且该模型也有这个方法:

public function FullName()
{
    return "{$this->name} {$this->surname}";
}
Run Code Online (Sandbox Code Playgroud)

如果我提出下一个请求:

$p = $people->all();
Run Code Online (Sandbox Code Playgroud)

我将获得以姓名作为属性的集合,如何为每个请求执行函数all()

最佳实践是什么?

Ken*_*rna 14

好吧,取决于你想要什么样的结果。


选项 A:在数组的所有项目中都有namesurname和。full_name

以利亚撒的回答是正确的,但有点不完整。

1. 在模型中定义一个新的访问器。

这将在您的模型中定义一个新属性,就像namesurname。当定义了新的属性后,您只需$user->full_name获取该属性即可。

正如文档所述,要定义访问器,您需要在模型中添加一个方法:

// The function name will need to start with `get`and ends with `Attribute`
// with the attribute field in-between in camel case.
public function getFullNameAttribute() // notice that the attribute name is in CamelCase.
{
    return $this->name . ' ' . $this->surname;
}
Run Code Online (Sandbox Code Playgroud)

2. 将属性附加到模型中

这将使该属性像任何其他属性一样被考虑,因此每当调用表的记录时,该属性都会被添加到该记录中。

要实现此目的,您需要在模型的受保护配置属性中添加这个新值,如文档$appends中所示:

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
     // notice that here the attribute name is in snake_case
    protected $appends = ['full_name'];
}
Run Code Online (Sandbox Code Playgroud)

3. 确保该属性是visible

请注意文档的这个重要部分:

将属性添加到附加列表后,它将包含在模型的数组和 JSON 表示形式中。附加数组中的属性也将遵循模型上配置的visible和 设置。hidden

4.查询您的数据。

当执行以下操作时:

$p = $people->all();
Run Code Online (Sandbox Code Playgroud)

$p数组应该具有namesurname以及full_name每个项目的新属性。


选项 B:仅获取用于特定目的的全名。

查询时可以执行以下操作,迭代每个结果以获取属性。

现在要做到这一点,你可以用一个句子迭代集合foreach,但考虑到每当查询数据时,返回的数组始终是一个Collection实例,所以你只需使用该map函数:

$full_names = $p->map(function ($person) {
    // This will only return the person full name,
    // if you want additional information just custom this part.
    return $person->fullname;
});
Run Code Online (Sandbox Code Playgroud)

使用集合高阶消息,它可以更短:

$full_names = $p->map->fullname;
Run Code Online (Sandbox Code Playgroud)