2016-08-17 52 views
1

我有Laravel口才一流CollageLaravel雄辯節省關係模型失敗

class Collage extends Model 
{ 

    /** 
    * Get the User that owns this Collage. 
    */ 
    public function user() 
    { 
     return $this->belongsTo('App\User'); 
    } 
} 

拼貼遷移模式

Schema::create('collages', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->integer('user_id')->unsigned(); 
      $table->string('name')->nullable(); 
      $table->timestamps(); 
     }); 

User

class User extends Authenticatable 
{ 
    /** 
    * Get all Collages that belongs to this User. 
    */ 
    public function collages() 
    { 
     return $this->hasMany('App\Collage'); 
    } 
} 

但是當我做這個鼓搗

$user = App\User::find(1)->first(); 
$collage = new App\Collage; 
$collage->name = 'Collage'; 
$collage->user = $user; 

//and save 
$collage->save(); 

拋出我的錯誤QueryException

General error: 1 table collages has no column named user 
+0

似乎要添加新用戶拼貼? – KmasterYC

+0

不,我只是想廣告用戶ID(誰擁有這個拼貼)拼貼。 –

+0

我想,從我看到你需要改變關係(我假設你的列):'$ this-> hasMany('App \ User','user_id','id');'和'return $ this - > hasMany('App \ Collage','id','user_id');' –

回答

1

變化

$collage->user = $user 

$collage->user_id = $user->id 
1

更新您的模式,使關係,

Schema::create('collages', function (Blueprint $table) { 
    $table->increments('id'); 
    $table->integer('user_id')->unsigned(); 
    $table->foreign('user_id')->references('id')->on('users'); 
    $table->string('name')->nullable(); 
    $table->timestamps(); 
}); 

這樣Laravel雄辯會自動作出的關係引用。

+0

是的,我已經添加了這一行,但仍然相同,我使用sqlite,可能是sqlite的原因呢? –