繁体   English   中英

如何 select 行在 Laravel Eloquent 方法或 Z9778840A0100CB305C98287674

[英]How to select rows having same column condition in Laravel Eloquent method or SQL

我有一个包含列的表“product_attribute_option”

product_id    attribute_id    attribute_option_id
 1             9                    15
 1             15                   23
 2             9                    15
 2             11                   18
 2             12                   19
 3             9                    15
 3             15                   23

现在我想按属性选项过滤产品。

如何获得具有attribute_option_id 15和23的不同product_ids?

您可以使用聚合和having子句:

select product_id
from t
where attribute_option_id in (15, 23)
group by product_id
having count(distinct attribute_option_id) = 2;

 

使用以下代码:

$products = Products::select('product_id')
    ->whereIn(attribute_option_id, [15, 23])
    ->distinct('attribute_option_id')
    ->groupBy('product_id')
    ->get();
    

确保关系[attribute,option]的名称是正确的

attributes 是产品有很多属性,option 是属性有一个或多个选项

`$products = Products::query()
    ->whereHas('attributes',function($q){
        $q->whereHas('option',function($q){
          $q->whereIn('id',[15,23]))})
    ->pluck('product_id')->toArray();`

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM