2016-06-16 6 views
0

のカテゴリのみを選択しています。私はproduct_idsにある製品を持つカテゴリを選択したい(他のクエリから取得する)。私は、上記のクエリでもproduct_idsにおける製品ではありません(空の配列でない場合produc_idで)場合は、すべてのカテゴリを選択しますLaravelは、製品IDが

$categories = Category::with(['products' => function ($query) use($product_ids) { 
    $query->whereIn('id', $product_ids); 
    }]) 
    ->get(); 

を試みたが、私はちょうどproduct_ids.pleaseヘルプの製品を持っているこれらのカテゴリを選択します

答えて

0

私はちょうどwhereHas

$categories = Category::with(['products' => function ($query) use($product_ids) { 
     $query->whereIn('id', $product_ids); 
    }]) 
->whereHas('products', function ($q) use($product_ids) { 
     $q->whereIn('id', $product_ids); 
    }) 
    ->get(); 
0

使用whereHas

$categories = Category::whereHas('products', function ($query) use($product_ids) { 
    $query->whereIn('id', $product_ids); 
    }) 
    ->get(); 
を追加することによってそれを解決0
+0

はい、しかし、where_asは、そのカテゴリのすべての製品をproduct_idsに入れなくても、私が 'with'と使用したものをフィルタリングする場合でも、 – sanu

+0

[docs](https://laravel.com/docs/5.2 /雄弁な関係#クエリ関係)? products_idリストから製品を持つすべてのカテゴリを取得します。 – huuuk

関連する問題