如何以 laravel 方式从远距离关系中获取计数?

How to fetch count from distant relationship in laravel way?

我正在尝试获取与给定类别中的产品相关联的产品数量的所有属性。

table结构

属性table:

| id  | name | value | filterable |

产品table:

| id  | name |

类别table:

| id  | name |

attribute_product 枢轴 table:

| id  | attribute_id | product_id

category_product 枢轴 table:

| id  | category_id | product_id

下面是我的模型的样子。

属性

public function products(){
        return $this->belongsToMany('App\Models\Product');
    }

产品

public function attributes(){
        return $this->belongsToMany('App\Models\Attribute');
    }

public function categories(){
        return $this->belongsToMany('App\Models\Category');
    }

类别

public function products(){
        return $this->belongsToMany('App\Models\Product');
    }

我可以使用以下查询获取与给定类别中的产品关联的所有属性。


Attribute::where('filterable', '=', 1)
->whereHas('products.categories', function (Builder $query) use ($category) {

$query->where('category_product.category_id', '=', $category->id);

})->get();

但是,我不知道应该如何获取产品数量。

我开始测试查询构建器以实现此目的,但条件是枢轴似乎绑定的位置 attribute_product.attribute_id 作为字符串值而不是列值。

$data = DB::table('attributes')->where('filterable', '=', true)
->whereExists(function ($query) {
$query->select('*')->from('products')
->join('attribute_product', function ($join){
    $join->on('products.id', '=', 'attribute_product.product_id');
})->where('attributes.id', '=', 'attribute_product.attribute_id');

})->get();

下面或多或少是我需要发送到数据库的最终 SQL 查询

select `attributes`.*, 
(SELECT 
count(*) from `products` 
inner join `attribute_product` on `products`.`id` = `attribute_product`.`product_id` 
where `attributes`.`id` = `attribute_product`.`attribute_id`) as `products_count` 
from `attributes` where `filterable` = 1 
and EXISTS 
(select * from `products` inner join `attribute_product` on `products`.`id` = `attribute_product`.`product_id` 
where `attributes`.`id` = `attribute_product`.`attribute_id` 
and EXISTS 
(select * from `categories` inner join `category_product` on `categories`.`id` = `category_product`.`category_id` 
where `products`.`id` = `category_product`.`product_id` and `category_product`.`category_id` = 9))

请大佬帮我用laravel的方式获取相关产品数量的属性。

查看

 withCount('relation_name') 

eloquent 中的方法 例如:

 $posts = App\Post::withCount([
    'comments',
    'comments as pending_comments_count' => function (Builder $query) {
    $query->where('approved', false);
    }
])->get();

我设法通过以下查询在一个请求中获得了所有结果。谢谢! @athul 指示方向。

Attribute::where('filterable', '=', 1)->whereHas('products.categories', function (Builder $query) use($category) {
                    $query->where('categories.id', '=', $category->id);
                })
                ->withCount(['products' => function ($query) use($category) {
                    $query->whereHas('categories', function (Builder $query) use ($category) {
                        $query->where('categories.id', '=', $category->id);
                  });
           }])->get();