【发布时间】:2022-01-10 07:49:08
【问题描述】:
我的模型中有一对多的关系。基本上是Category 和Product。一个产品只能有一个类别,但一个类别可以有多个产品。下面的代码有效:
return Category::select('id', 'name')->whereIn('id', $categories)->with('products')->get();
它返回一个产品密钥,其中包含数据库中的产品列,但是当我使用急切加载时,它只返回一个空集:
return Category::select('id', 'name')->whereIn('id', $categories)->with(['products' => function($query){
$query->limit(5);
}])->get();
我也尝试过像 return $query->limit(5); 这样添加 return 关键字,但仍然没有成功。
我也尝试过像这样指定列:
return Category::select('id', 'name')->whereIn('id', $categories)->with('products:id,name')->get();
但它仍然返回一个空数据集。
由于我正在构建 API,因此 JSON 数据如下所示:
[
{
"id": 161,
"name": "Health & Personal Care",
"products": []
},
{
"id": 256,
"name": "Makeup & Fragrances",
"products": []
},
]
我的表结构:
categories (there's no product_id column, since it's one to many)
+----+------+
| id | name |
+----+------+
| | |
+----+------+
| | |
+----+------+
| | |
+----+------+
product
+----+------+-------+-------------+
| id | name | price | category_id |
+----+------+-------+-------------+
| | | | |
+----+------+-------+-------------+
| | | | |
+----+------+-------+-------------+
| | | | |
+----+------+-------+-------------+
我的类别模型是这样声明的:
public function products()
{
return $this->hasMany(Product::class);
}
产品型号为:
public function category()
{
return $this->belongsTo(Category::class);
}
【问题讨论】:
-
你检查过关系的定义是否正确
-
@rubys 我会在上面的表格中添加
-
只需尝试简单查询而不选择特定列 Category::whereIn('id', $categories)->with('products')->get();
-
@BhargavRangani 但我想选择列并且每个类别只显示 5 个项目。
标签: laravel eloquent eager-loading