那要看你想要什么样的结果了。
选项 A:在数组的所有项中包含 name、surname 和 full_name。
Eleazar 的回答是正确的,但有点不完整。
1。在模型中定义一个新的访问器。
这将在您的模型中定义一个新属性,就像name 或surname。定义新属性后,只需$user->full_name即可获取该属性。
正如documentation 所说,要定义访问器,您需要在模型中添加一个方法:
// 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;
}
2。将属性附加到模型
这将使该属性被视为与任何其他属性一样,因此每当调用表的记录时,该属性将被添加到记录中。
要完成此操作,您需要在模型的受保护的$appends 配置属性中添加这个新值,正如您在documentation 中看到的那样:
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'];
}
3。确保此属性为visible
请注意docs 的这一重要部分:
一旦属性被添加到附加列表中,它将被
包含在模型的数组和 JSON 表示中。
appends 数组中的属性也将遵循 visible 和
hidden 模型上配置的设置。
4。查询您的数据。
执行以下操作时:
$p = $people->all();
$p 数组应具有 name、surname 以及每个项目的新 full_name 属性。
选项 B:只为特定目的获取 full_name。
查询时可以做如下操作,对每个结果进行迭代获取属性。
现在,您可以使用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;
});