简单的mutator与SQL Query拧紧? - Laravel

时间:2017-04-23 22:43:31

标签: php laravel

我希望能够通过user_id mutator设置setUserIdAttribute,但它不起作用。当我注释掉mutator时,代码工作正常。下面是我的代码和生成的QueryException错误。请帮忙!

// EventController.php
public function store(Request $request)
{
    Event::create([
      'name'=>'myName',
      'user_id'=>'1'
    ]);
    return 'Success!';
}
// Event.php
class Event extends Model
{
    protected $fillable = ['name', 'user_id'];

    // It works as expected if I comment this out.
    public function setUserIdAttribute($value)
    {
        // I know this code will run. If i do echo 'foo' it works.
        return '1';
    }
}
// The migration file
public function up()
{
    Schema::create('events', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('user_id')->unsigned();
        $table->foreign('user_id')->references('id')->on('users');
        $table->timestamps();
    });
}
// The error I get
SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value (SQL: insert into `events` (`name`, `updated_at`, `created_at`) values (myName, 2017-04-23 22:28:31, 2017-04-23 22:28:31))

1 个答案:

答案 0 :(得分:1)

我认为$this->attributes['attribute_name']是变异的正确方法。

// Event.php
class Event extends Model
{
  protected $fillable = ['name', 'user_id'];        
  // It works as expected if I comment this out.
  public function setUserIdAttribute($value)
  {
    // Set Attribute's value.
    $this->attributes['user_id'] = Auth::id();
  }
}