简体   繁体   中英

Laravel - Eloquent ORM Relationship Query

I have 5 tables:

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

The tables structure are as follows:

news

id
title
description

tags

id
title

filters

id
title

news_tag

id
tag_id
news_id

tag_filter

id
tag_id
filter_id

Let's say for example my tables have the following records:

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

The relationships in my models are as follows:

News model

public function tags(){

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

Tag model

public function news(){

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

public function filters(){

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

Filter model

public function tags(){

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

Let's say my route is as follows: Route::get('news/filter/{filter_id}','NewsController@getNews');

I want to retrieve all the news related to tag_id 1 when I pass filter_id 1 to my route. Anyone can help me how to do this in my controller?

There is no simple way to do this, but you can use something like this:

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

Note select() instruction. If you skip it, Laravel will load invalid fields into your News models. It's must-have when you do joins in Eloquent Builder.

If you want to eager load relations in this case, use with() method of the query builder.

You can try some nested whereHas instead of join. I'm not sure about performance.

    $filterId = 1;
    News::whereHas('tags', function($q1) use ($filterId) {
        $q1->whereHas('filters', function($q2) use ($filterId) {
            $q2->where('id', '=', $filterId);
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM