2017-04-23 4 views
0

setUserIdAttributeミューテータでuser_idを設定したいが、それはうまくいかない。ミューテータをコメントアウトすると、コードは正常に動作します。以下は私のコードと結果のQueryExceptionエラーです。助けてください!SQLクエリーを使用した単純なミューテータ - Laravel

// 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

私は$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(); 
    } 
} 
+0

ありがとうございます!私はそれが動作するかどうかを確認するためにこれを試してみます。私は実際に 'Auth :: id()'を使うつもりでしたが、エラーとは関係がないことを知っていましたので、私は物事を単純化しました。 –

+0

それは働いた!あなたの答えを自由に編集して、良いユースケースとして 'Auth :: id()'を組み込んでください。 –

+0

うれしかったです。 :) – imrealashu

関連する問題