1 回答

TA貢獻1828條經驗 獲得超6個贊
belongsToMany 在模型中定義關系
public function category()
{
return $this->belongsToMany(Category::class);
}
不要忘記為Post和Category 關聯添加一個中間數據透視表
因為你沒有 RTFM,這里有一個完整的工作示例
PostTableSeeder.php
public function run()
{
factory(App\Post::class, 300)->create()->each(function (App\Post $post) {
$post->categories()->attach([
rand(1, 5),
rand(6, 14),
rand(15, 20),
]);
});
}
Post.php 模型
public function categories()
{
return $this->belongsToMany('App\Category');
}
Category.php 模型
public function posts()
{
return $this->belongsToMany('App\Category');
}
category_post 表遷移
Schema::create('category_post', function (Blueprint $table) {
$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('category_id');
});
希望這可以幫助 :)
- 1 回答
- 0 關注
- 216 瀏覽
添加回答
舉報