Laravel - Eloquent ORM 关系查询

3

我有5个表:

 1. news
 2. tags
 3. filters
 4. news_tag
 5. tag_filters

表结构如下:
news
id
title
description

标签

id
title

过滤器

id
title

news_tag

id
tag_id
news_id

tag_filter

id
tag_id
filter_id

假设我的数据表包含以下记录:
news: id = 1 title = News_1 Description = Details for News_1
tags: id = 1 title = PHP
filters: id = 1 title = PHP News
news_tag: id = 1 tag_id = 1 news_id = 1
tag_filter: id = 1 tag_id = 1 filter_id = 1

我的模型关系如下:
新闻模型:
public function tags(){

    return $this->belongsToMany('App\Tag', 'news_tag');
}

标签模型

public function news(){

    return $this->belongsToMany('App\News', 'news_tag');
} 

public function filters(){

    return $this->belongsToMany('App\Filter', 'tag_filter');
}

过滤器模型

public function tags(){

    return $this->belongsToMany('App\Tag', 'tag_filter');
}

假设我的路由如下:Route :: get('news/filter/{filter_id}','NewsController@getNews'); 当我将filter_id 1传递到我的路由时,我想检索与tag_id 1相关的所有新闻。 有人可以帮助我如何在我的控制器中实现这一点吗?
2个回答

0

没有简单的方法来做到这一点,但是您可以使用类似于以下内容的东西:

News::select("news.*")
  ->join('tags'...)
  ->join('filters'...)
  ->where('filter_id',...)
  ->where('tag_id',...)
  ->get();

注意 select() 指令。如果你跳过它,Laravel将会把无效的字段加载到你的News模型中。在Eloquent Builder进行关联查询时这是必须的。
如果你想在这种情况下提前加载关系,请使用查询构建器的with()方法。

请您能否详细说明一下连接(join)和筛选(where)条件呢?问题在于tag_id与news_id有关联。因此,基本上我需要获取所有与我传递到路由的filter_id相关联的tag_id,然后查找与这些tag_id相关联的所有news_id。 - Nas Atchia

0
您可以尝试使用嵌套的 whereHas 而非 join。关于性能我不是很确定。
    $filterId = 1;
    News::whereHas('tags', function($q1) use ($filterId) {
        $q1->whereHas('filters', function($q2) use ($filterId) {
            $q2->where('id', '=', $filterId);
        });
    });

它可能会很慢。 - Vladislav Rastrusny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接