laravel - 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);
我想要属于颗粒类别的产品。例如:图书类别的产品。
解决方案
您可以使用查询构建器的“whereHas”方法,如下所示:
$products = Product::with('category')
->whereHas('category', function ($query) use ($cid) {
return $query->where('id', $cid);
}
->inRandomOrder()
->paginate(20);
该方法的第一个参数是要用作过滤器的关系的名称,第二个参数是一个函数,用于修改搜索相关对象是否存在的查询。
推荐阅读
- mysql - 仅过滤每个主外键关系上的连接
- javascript - 使用 TASKER 搜索 Web 场景中的变量
- node.js - 无法使用节点 js 在套接字上接收数据
- python - 使用 sort_value(inplace=True) 对数据框进行排序时出现错误
- macos - 如何通过mac终端中的公共IP SSH到私人IP?
- angular - 登录时,Angular 6 auth guard 停留在空白页面上
- php - WooCommerce 中的特定产品除外的最低购物车数量
- c++ - 如何在 bazel 中同时处理外部依赖项和我的项目?
- javascript - 在 Three.js 中围绕任意轴旋转物体,就像月球围绕地球旋转一样。
- django - “用户”对象没有属性“图像”