问题
Each Article belongs to many Categories. Each User has many Categories. I want to retrieve all the Articles which has the User’s Categories. For each of these relationships below I have my own pivot tables.
article_cat
id | articleID | categoryId
users_cats
id | user_details_id | categories_id
Relationships.
Articles.php
public function categories()
{
return $this->belongsToMany('App\Categories', 'article_categories', 'articleID', 'categoryID');
}
UserDetails.php
public function Categories(){
return $this->belongsToMany('App\Categories', 'users_cats', 'user_details_id', 'categories_id');
}
Categories.php
public function articles(){
return $this->belongsToMany('App\Article', 'article_categories', 'categoryID', 'articleID');
}
public function UserDetails(){
return $this->HasMany('App\UserDetails', 'users_cats', 'user_details_id', 'categories_id');
}
I have tried to use HasMany through but It doesn’t work with a many to many relationship as far as I can tell.
Currently (as a sort of “work around”) Ive been using this. Ive pulled up a list of the user's Categories and searching through all of ids and pulling the relevant Article and forming a collection from it in UserDetails.php
$user = self::find($this->id);
$user = $user->Categories;
foreach ($user as $item) {
foreach ($item->articles as $article)
$article1[] = Article::find($article->id);
}
$articles = collect($article1)->sortByDesc('date')->unique();
return $articles;
However I don’t think it will scale well with increasing data (its already producing over 1k queries with only 1000 articles, taking over 8 seconds to load).
Any ideas?
回答1:
You could use an IN query. Or a subquery.
Article::whereIn('id', $user->Categories::all->lists('id')->toArray() )
$category_id = $user->Categories::all->lists('id')->toArray();
Article::whereIn('id', function($query) use ($category_id){
$query->select('categories_id')
->from(with(new Category)->getTable())
->whereIn('category_id', $categoryID )
})->get();
来源:https://stackoverflow.com/questions/42181700/relationship-hasmanythrough-with-many-to-many-relationship