首页 > 解决方案 > Laravel eloquent contitional join 与 contitions 作为传递 id

问题描述

我有模型

Product       
  id                  
  name                 
  ....
  ....

例子:

1 | Product A 
2 | Product b  
3 | Product c

Category       
  id                 
  category           
  .....

例子:

1 | Books    
2 | cds
3 | paper

ProductCategory      
  id                          
  product_id                  
  category_id
  ......

example: 
1 | 1 | 1
2 | 1 | 2
3 | 2 | 3

我的模型是这样的:

产品型号

 public function category()
    {
        return $this->hasMany('App\ProductCategory', 'product_id', 'id');
    }

类别模型

public function product_category()
    {
        return $this->belongsTo('App\ProductCategory', 'category_id', 'id');
    }

产品类别模型

public function category()
    {
        return $this->belongsTo('App\Category', 'category_id', 'id')->where('status', '=', 1);
    }

我的查询是写 Laravel Eloquent 查询,其中产品类别是“cds”

$products = Product::with('category')
        // ->where('category_id', $cid)
        ->inRandomOrder()
        ->paginate(20);

我想要属于颗粒类别的产品。例如:图书类别的产品。

标签: laraveljoineloquentconditional-statements

解决方案


您可以使用查询构建器的“whereHas”方法,如下所示:

$products = Product::with('category')
    ->whereHas('category', function ($query) use ($cid) {
        return $query->where('id', $cid);
    }
    ->inRandomOrder()
    ->paginate(20);

该方法的第一个参数是要用作过滤器的关系的名称,第二个参数是一个函数,用于修改搜索相关对象是否存在的查询。


推荐阅读