laravel在set属性和除列上的质量分配

时间:2018-12-10 11:08:32

标签: laravel eloquent

我的数据库中没有“ full_name”列,但是我的数据库中没有“ first_name”和“ last_name”列。

这是我的表格:

<form method="POST" action="">
    <input type="text" name="first_name">
    <input type="text" name="last_name">
</form>

这是我的模特

class User extends Model
{
    protected $guarded = ['first_name', 'last_name'];

    public function setFullNameAttribute()
    {
        $this->attributes['full_name'] = $this->attributes['first_name'].' '.$this->attributes['last_name'];
    }
}

这是我的控制器类中的代码

public function store(StoreUser $request)
{
    $validated = $request->validated();
    $user = Auth::user();
    $user->update($validated);
}

提交表单后,出现错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'first_name' in 'field list'

我知道是什么原因,是因为$guarded = ['first_name', 'last_name']

但是,如果我没有保护这些字段,则会出现错误:

"Undefined index: first_name"

我知道是什么原因造成的,是因为我的数据库中没有“ first_name”列。


  

所以我陷入了困境,不知道如何将“ full_name”更新到数据库中,   并避免分配“ first_name”和“ last_name”字段。

PS,我不使用$user->save()是因为在现实世界中有大量工作需要更新。

2 个答案:

答案 0 :(得分:1)

根据输入来适应模型/存储库是控制者角色。

您的模型应该只反映数据:

class User extends Model
{
    protected $guarded = ['full_name'];
}

您的控制器

public function store(StoreUser $request)
{
    $validated = $request->validated();
    $user = Auth::user();
    if (isset($validated['first_name']) && isset($validated['last_name'])) {
        $validated['full_name'] = $validated['first_name'].' '.$validated['last_name'];
    }
    unset($validated['first_name'], $validated['last_name']);
    $user->update($validated);
}

但是如果您想继续使用您的方法,我建议您多收取更新方法的费用

class User extends Model
{
    protected $guarded = ['first_name', 'last_name'];

    /**
    * @param array $attributes
    * @param array $options
    * @return bool
    */
    public function update(array $attributes = [], array $options = [])
    {
        if (isset($attributes['first_name']) && isset($attributes['last_name'])) {
            $attributes['full_name'] = $attributes['first_name'].' '.$attributes['last_name'];
        }
        unset($attributes['first_name'], $attributes['last_name']);
        return parent::update($attributes, $options);
    }
}

答案 1 :(得分:1)

最简单的解决方案是:

class User extends Model
{
    protected $fillable = ['full_name'];

}

存储功能如下:

public function store(StoreUser $request)
{
    $validated = $request->validated();
    $validated['full_name'] = $validated['first_name'].' '. $validated['last_name'];
    $user = Auth::user();
    $user->update($validated);
}
相关问题