2017-04-23 51 views
0

我想通過setUserIdAttribute mutator來設置user_id,但它不起作用。當我將mutator註釋掉時,代碼正常工作。下面是我的代碼和由此產生的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