【问题标题】:Additional attributes in Laravel all requestLaravel 所有请求中的附加属性
【发布时间】:2018-12-01 08:19:41
【问题描述】:

美好的一天。 例如,我有一个带有字段/属性的模型People

name
surname

而且模型也有这个方法:

public function FullName()
{
    return "{$this->name} {$this->surname}";
}

如果我提出下一个请求:

$p = $people->all();

我将收集带有姓名和姓氏作为属性的集合 我如何在all() 请求中为每个函数执行?

最佳做法是什么?

【问题讨论】:

  • foreach ($peoples->all() as $people) { var_dump($people->name); }

标签: laravel oop model-view-controller eloquent


【解决方案1】:

那要看你想要什么样的结果了。


选项 A:在数组的所有项中包含 namesurnamefull_name

Eleazar 的回答是正确的,但有点不完整。

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

这将在您的模型中定义一个新属性,就像namesurname。定义新属性后,只需$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 数组中的属性也将遵循 visiblehidden 模型上配置的设置。

4。查询您的数据。

执行以下操作时:

$p = $people->all();

$p 数组应具有 namesurname 以及每个项目的新 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;
    });

【讨论】:

  • 选项 B 可以简化为:$full_names = $p->pluck('fullname');。即使使用附加到模型的访问器。
  • @IvankaTodorova 请注意,在我的回复中,选项 B 独立于选项 A 的步骤,因此尚未附加访问器,但是是的,它可以按照您建议的方式轻松访问 :) .
  • 几乎一切都应有尽有,但需要以数组或json的形式表示数据
  • @DmitriySkogorev 抱歉,我没听懂你的最后一个问题。
【解决方案2】:

在您的模型中编写一个函数来连接名称

public function getFullNameAttribute() {
        return ucfirst($this->first_name) . ' ' . ucfirst($this->last_name);
    }

现在你可以这样称呼它

$user = User::find(1);
echo $user->full_name;

or 
Auth::user()->full_name;

【讨论】:

    【解决方案3】:

    我使用以下:

    public function getFullNameAttribute()
    {
        return "{$this['name']} {$this['lastname']}";
    }
    

    然后,我将其添加到 appends 中:

    class User extends Authenticatable {
        protected $appends = ['fullname'];
    }
    

    你怎么看?

    【讨论】:

    • 我认为不是我搜索的内容
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-30
    • 2017-02-20
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多