我有Laravel Eloquent班Collage
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 :(得分: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 Eloquent会自动引用这段关系。
答案 1 :(得分:1)
更改
$collage->user = $user
要强>
$collage->user_id = $user->id