关系 HasManyThrough 与多对多关系 [英] Relationship HasManyThrough with Many to Many relationship

查看:33
本文介绍了关系 HasManyThrough 与多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每篇文章属于多个类别.每个用户都有许多类别.我想检索所有具有用户类别的文章.对于下面这些关系中的每一个,我都有自己的数据透视表.

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

article_cat

id |文章ID |类别标识

id | articleID | categoryId

users_cats

id |user_details_id |category_id

id | user_details_id | categories_id

关系.

文章.php

public function categories()
    {
        return $this->belongsToMany('AppCategories', 'article_categories', 'articleID', 'categoryID');
    }

UserDetails.php

 public function Categories(){
        return $this->belongsToMany('AppCategories', 'users_cats', 'user_details_id', 'categories_id');
    }

Categories.php

public function articles(){
    return $this->belongsToMany('AppArticle', 'article_categories', 'categoryID', 'articleID');
}
public function UserDetails(){
    return $this->HasMany('AppUserDetails', 'users_cats', 'user_details_id', 'categories_id');
}

我曾尝试使用 HasMany,但据我所知,它不适用于多对多关系.

I have tried to use HasMany through but It doesn’t work with a many to many relationship as far as I can tell.

目前(作为一种变通")我一直在使用它.我已经拉出用户的类别列表并搜索所有 id 并拉出相关文章并在 UserDetails.php 中从中形成一个集合

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;

然而,我认为它不会随着数据的增加而很好地扩展(它已经产生了超过 1k 的查询,只有 1000 篇文章,加载时间超过 8 秒).

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).

有什么想法吗?

推荐答案

您可以使用 IN 查询.或者子查询.

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();

这篇关于关系 HasManyThrough 与多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆