【问题标题】:Laravel eloquent contitional join with contitions as passing idsLaravel 雄辩的条件连接,条件为传递 id
【发布时间】:2020-11-23 10:27:40
【问题描述】:

我有模型

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);

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

【问题讨论】:

  • 所以您只想要具有 category_id 是特定值的类别的产品?为什么有 3 个模型呢?
  • 因为一个产品可以有多个类别一对多的关系

标签: laravel join eloquent conditional-statements


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 2015-08-08
    • 2017-11-19
    • 1970-01-01
    • 2018-12-09
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多