首页 > 解决方案 > 基于关系 laravel 过滤模型

问题描述

所以我的代码是

$categories=Category::where('user_id', $store->id)->whereHas('childrenCategories', function($q) use ($id){
            $q->where('user_id', $id);
        })->orwhereHas('products', function($q) use ($id) {
            $q->where('auth_id', $id);
        })->with('products', 'childrenCategories')->latest()->get();

我想获取所有具有给定 ID 的子类别和产品,但此代码似乎不起作用。作为具有除 id 之外的 user_id 的子类别也被返回。抱歉,我对 Laravel 比较陌生。我认为这将是一个很好的提问平台。另外,如果您愿意,我可以分享这些关系。

标签: phplaraveleloquent

解决方案


I solved this with the following. Thanks, @lagbox for your time.

$categories = Category::with(['childrenCategories' => 
$childrenClosure = function ($query) use ($id) {$query->where('user_id', $id);}, 'products' 
=> $productsClosure = function ($query) use ($id) {$query->where('auth_id', $id);}])
->where('user_id', $store->id)
->where(function ($query) use ($childrenClosure, $productsClosure) {$query->whereHas('childrenCategories', $childrenClosure)
->orWhereHas('products', $productsClosure);})
->latest()
->get(); 


推荐阅读