draw62188 2015-09-15 14:36
浏览 34
已采纳

通过关系查询数据透视表

I'm Using Laravel 5.1 and have these four database tables

posts containing posts from Facebook. The posts table has a foreign key page_id. It's a refernece to the

pages table, which contains all facebook pages.

category table contains data for the categories in my project, e.g. funny, videos, etc.

category_page is a pivot table which saves the category_id and the page_id


What I now want to do, is to get all posts, that have been posted by a page in a specific category.

So, let's assume I have three pages

1: Mesut Oezil
2: Borussia Dortmund
3: BMW

The first two pages are in the category sports and the last one in cars. Now I want to get every post that has been posted by the pages from the category sport.

I have already defined the relation ships

Class Page:

public function categories()
{
    return $this->belongsToMany(Category::class);
}

Class Category:

public function pages()
{
    return $this->belongsToMany(Page::class);
}

Now, I'm getting my posts

$topPosts = (new Post)->where('fb_created_time', '>', Carbon::today()->toDateTimeString())
    ->visible()
    ->orderBy('total_count', 'desc');

And now I want to additional filter only the posts from the pages in a specific category. I managed to get pages from a specific category with this code here

$pages = Page::with('categories')
    ->whereHas('categories', function ($query){
        return $query->where('category_id', 1);
    })->get();

But how would I chain this into the posts? Or is it even good to use whereHas? What's the best practice here?

  • 写回答

1条回答 默认 最新

  • dongtaijiao7140 2015-09-15 15:57
    关注

    If I'm understanding right, you want to get posts, what belongs to a specific category, through pages.

    In this case your setup is fine, you can make queries through relationships:

    $category_id = 2;
    Post::whereHas('page.categories', function($q) use($category_id) {
        $q->where('categories.id', $category_id);
    })->get();
    

    In your Post class:

    public function page()
    {
        return $this->belongsTo(Page::class);
    }
    

    It will make one nested query.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法