【发布时间】:2020-05-06 09:37:42
【问题描述】:
我有三个表,我想关联这三个表,但我不知道如何。
我有一个用户表和两个帖子和类别表,类别也将类别和子类别存储在同一个表上(使用类型列分隔)。
帖子和用户也有一个数据透视表以及帖子和类别。但我想通过以下类别获取用户帖子:
类别或子类别 -> 帖子 -> 用户
类别模型:
class Category extends Model
{
protected $fillable = ['name', 'description', 'type', 'category_id','post_id'];
public function posts() {
return $this->belongsToMany(Post::class)->withPivot('post_id');
}
}
后模型:
class Post extends Model {
public function users() {
return $this->belongsToMany(User::class, 'post_user','post_id', 'user_id')->withTimestamps();
}
public function categories() {
return $this->belongsToMany(Category::class)->withPivot('category_id');
}
用户模型:
class User extends Authenticatable {
public function posts() {
return $this->belongsToMany(Post::class, 'post_user', 'user_id', 'post_id')->withTimestamps();
}
然后在控制器中我只有这个
$posts = Category::with('posts')->get();
我不知道如何关联这 3 个表格。也许我只需要在 3 个表之间创建一个数据透视表?
编辑:感谢 Qirel 帮助我关联表格:
Category::with('posts.users');
然后我只想显示特定用户发布帖子的类别,例如
Category::with('posts.users')->where('user.id',1);
有可能吗?
【问题讨论】:
-
您可以嵌套关系,例如
Category::with('posts.users');(在posts和posts.users关系上都渴望加载)。用户与帖子相关,所以应该有一个post_user数据透视表,并且一个类别链接到一个帖子,所以应该有一个category_post数据透视表。通过将这些组合在一起,您可以找出哪些用户在哪些类别中发布过帖子,反之亦然。 -
那么我可以显示用户发帖的类别吗?喜欢
post.users where id = 1? -
是的,
Category::with('posts.users')->whereHas("posts.users", function($query) { $query->where("id", 1); });或Category::with('posts.users', function($query) { $query->where("id", 1); });(一个只是过滤关系数据并选择类别,另一个检查是否有关系数据)。 -
在两个选项中都返回这个:
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in where clause is ambiguous (SQL: select * from `categories` where exists (select * from `posts` inner join `category_post` on `posts`.`id` = `category_post`.`post_id` where `categories`.`id` = `category_post`.`category_id` and exists (select * from `users` inner join `post_user` on `users`.`id` = `post_user`.`user_id` where `posts`.`id` = `post_user`.`post_id` and `id` = 1))) -
在
category_post或post_user中是否有id列?
标签: php laravel eloquent pivot-table