Laravel-$ fillable已填充,仍然会出现MassAssignmentException

时间:2018-06-25 04:10:25

标签: php laravel

我有一个非常特殊的问题。我试图通过Tinker在数据库中创建一个新条目。每当我跑 App\User::find(1)->message()->create(['message' => 'Hello from Coleigh']);我收到MassASsignmentException。奇怪的是,我将变量名称放在我的可填充属性中。我不明白为什么要得到这个。

我一直在谷歌搜索答案,但是正如您从代码中看到的那样,我已将我的消息字段添加到两个可填充属性中。我完全不知道为什么laravel无法识别消息字段。

这是我的模特

namespace App;

use Illuminate\Database\Eloquent\Model;

    class Message extends Model
    {
        protected $fillable = ['message'];
        public function user() {
            return $this->BelongsTo(User::class);
        }
    }

<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use Notifiable;
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'message'
    ];
    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function profile()
    {
        return $this->hasOne('App\Profile');
    }

    public function roles() {
        return $this->BelongsToMany('App\Role');
    }

    public function hasRole($name) {
        foreach($this->roles as $role) {
            if ($role->name == $name) {
                return true;

            }

        }

        return false;

    }

    public function deposits() {
        return $this->hasMnay('App\Deposits');
    }

    public function isBlocked()
    {
        if ($this->banned) {
            return true;
        } else {
            return false;
        }
    }

    public function message() {
        return $this->hasMany(Message::class);
    }


}

3 个答案:

答案 0 :(得分:1)

在类消息中,您应该在$ fillable属性中再添加一列。

nohup

答案 1 :(得分:0)

使用save

$user = App\User::find(1);

$comment = new App\Message(['message' => 'Hello from Coleigh']);

$user->message()->save($comment);

否则,使用create时,您需要设置关系ID。

答案 2 :(得分:0)

似乎您在消息user_id中丢失了$fillablehttps://laravel.com/docs/5.6/eloquent#mass-assignment