通过关系查询数据透视表 table
Querying a pivot table through a relationship
我正在使用 Laravel 5.1 并拥有这四个数据库 tables
posts
包含来自 Facebook 的 post。 posts
table 有一个外键 page_id
。这是对
的引用
pages
table,其中包含所有 facebook 页面。
category
table 包含我项目中类别的数据,例如funny
、videos
等
category_page
是一个枢轴 table,它保存了 category_id
和 page_id
我现在想做的是获取所有 post 已被特定类别中的页面 post 编辑的内容。
所以,假设我有三个页面
1:梅苏特·厄齐尔
2: 多特蒙德
3: 宝马
前两页属于类别 sports
,最后一页属于 cars
。现在,我想获取 post 类别 sport
.
中的页面 post 的每个 post
我已经定义了关系
Class 页数:
public function categories()
{
return $this->belongsToMany(Category::class);
}
Class 类别:
public function pages()
{
return $this->belongsToMany(Page::class);
}
现在,我得到了我的 posts
$topPosts = (new Post)->where('fb_created_time', '>', Carbon::today()->toDateTimeString())
->visible()
->orderBy('total_count', 'desc');
现在我只想从特定类别的页面中额外过滤 post。我设法使用此代码从特定类别获取页面
$pages = Page::with('categories')
->whereHas('categories', function ($query){
return $query->where('category_id', 1);
})->get();
但是我如何将其链接到 post 中?还是使用 whereHas
更好?这里的最佳做法是什么?
如果我没理解错的话,您想通过页面获取属于特定类别的帖子。
这种情况下你的设置没问题,你可以通过关系进行查询:
$category_id = 2;
Post::whereHas('page.categories', function($q) use($category_id) {
$q->where('categories.id', $category_id);
})->get();
在你的 Post class:
public function page()
{
return $this->belongsTo(Page::class);
}
它将进行一次嵌套查询。
我正在使用 Laravel 5.1 并拥有这四个数据库 tables
posts
包含来自 Facebook 的 post。 posts
table 有一个外键 page_id
。这是对
pages
table,其中包含所有 facebook 页面。
category
table 包含我项目中类别的数据,例如funny
、videos
等
category_page
是一个枢轴 table,它保存了 category_id
和 page_id
我现在想做的是获取所有 post 已被特定类别中的页面 post 编辑的内容。
所以,假设我有三个页面
1:梅苏特·厄齐尔
2: 多特蒙德
3: 宝马
前两页属于类别 sports
,最后一页属于 cars
。现在,我想获取 post 类别 sport
.
我已经定义了关系
Class 页数:
public function categories()
{
return $this->belongsToMany(Category::class);
}
Class 类别:
public function pages()
{
return $this->belongsToMany(Page::class);
}
现在,我得到了我的 posts
$topPosts = (new Post)->where('fb_created_time', '>', Carbon::today()->toDateTimeString())
->visible()
->orderBy('total_count', 'desc');
现在我只想从特定类别的页面中额外过滤 post。我设法使用此代码从特定类别获取页面
$pages = Page::with('categories')
->whereHas('categories', function ($query){
return $query->where('category_id', 1);
})->get();
但是我如何将其链接到 post 中?还是使用 whereHas
更好?这里的最佳做法是什么?
如果我没理解错的话,您想通过页面获取属于特定类别的帖子。
这种情况下你的设置没问题,你可以通过关系进行查询:
$category_id = 2;
Post::whereHas('page.categories', function($q) use($category_id) {
$q->where('categories.id', $category_id);
})->get();
在你的 Post class:
public function page()
{
return $this->belongsTo(Page::class);
}
它将进行一次嵌套查询。