【问题标题】:How to get common models out of two many to many relationships in laravel?如何从laravel中的两个多对多关系中获取通用模型?
【发布时间】:2015-01-30 15:06:36
【问题描述】:

有 3 种型号:

Products belongstoMany Categories
Products belongstoMany Stores
Categories belongstoMany Products
Stores belongstoMany Products

如何找到属于特定类别和特定商店的所有产品?

这是我尝试过的:

Product::getAll()->join('categorie_product', 'categorie_product.product_id', '=', 'product.id')
                ->join('categorie', 'categorie.id', '=', 'categorie_product.categorie_id')
                ->where('categorie.name', '=', $categorieName)
                ->paginate(10);

有什么建议吗?谢谢..

P.S.:我想用 eloquent 来完成这个任务。 DB::* 可以,但我需要雄辩的实现,因为我使用 Dingo API 来完成一些 REST API。

【问题讨论】:

    标签: php laravel laravel-4 many-to-many eloquent


    【解决方案1】:

    使用whereHas 按关系过滤:

    Product::with('categorie','store')->whereHas('categorie', function($q) use ($categoryName){
                            $q->where('categories.name', $categoryName);
                        })->whereHas('store', function($q) use ($storeId){
                            $q->where('stores.id', $storeId);
                        })->paginate(10);
    

    别忘了使用with()eager load你的相关模型

    【讨论】:

    • 工作,就像一个魅力!将其编辑为包含 with()。谢谢!非常感谢您建议急切的负载:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-04
    • 2016-07-20
    • 2020-10-11
    • 1970-01-01
    • 2018-10-21
    相关资源
    最近更新 更多