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 关注
- 217 浏览
添加回答
举报