【问题标题】:Laravel - $fillable filled, still getting MassAssignmentExceptionLaravel - $fillable 填充,仍然得到 MassAssignmentException
【发布时间】:2018-06-25 04:10:24
【问题描述】:

我有一个非常特殊的问题。我正在尝试通过 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);
    }


}

【问题讨论】:

  • 我有一个类似的问题,它与时间戳有关。尝试将 public $timestamps = false; 放入您的 Message 类中。如果不起作用,请发布您的 MassAssignment 异常错误
  • 没用。我收到此错误:Illuminate/Database/Eloquent/MassAssignmentException with message 'message'
  • 为什么不先创建消息并将其附加给用户?
  • 我正在关注 YouTube 上的教程,他们就是这样做的。
  • 尝试重新启动 Tinker。每当您修改代码时,都需要重新启动 Tinker。

标签: php laravel


【解决方案1】:

在课堂信息中,您应该在 $fillable 属性中再添加一列。

protected $fillable = ['user_id', 'message'];

【讨论】:

    【解决方案2】:

    使用save

    $user = App\User::find(1);
    
    $comment = new App\Message(['message' => 'Hello from Coleigh']);
    
    $user->message()->save($comment);
    

    否则,您需要设置关系 ID。

    【讨论】:

      【解决方案3】:

      您在消息$fillable 中似乎缺少user_idhttps://laravel.com/docs/5.6/eloquent#mass-assignment

      【讨论】:

      • 试过了,没成功
      猜你喜欢
      • 2018-04-08
      • 2014-04-12
      • 2013-06-10
      • 2017-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-21
      • 1970-01-01
      相关资源
      最近更新 更多