2 回答

TA貢獻1921條經(jīng)驗 獲得超9個贊
我認為你的關(guān)系不正確,因為一個類別可以有很多博客
分類型號:
public function blogs(){ return $this->hasMany('App\Models\Blog'); }
和博客屬于一類
博客模型:
public function category(){ return $this->belongsTo('App\Models\Category', 'category_id'); }

TA貢獻2011條經(jīng)驗 獲得超2個贊
您需要在表blog_id中添加一列categories。對于一個hasOne關(guān)系,它是belongsTo攜帶它所屬表的id的模型。您的代碼應如下所示:
類別
Schema::create('categories', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('blog_id')->unsigned();
$table->string('title');
$table->timestamps();
$table->foreign('blog_id')->references('id')->on('blogs');
});
博客
Schema::create('blogs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('title', 100);
$table->string('description', 900);
$table->string('image');
$table->timestamps();
});
博客模式
public function category(){
return $this->hasOne('App\Models\Category');
}
品類模型
public function blogs(){
return $this->belongsTo('App\Models\Blog');
}
- 2 回答
- 0 關(guān)注
- 296 瀏覽
添加回答
舉報