我正在使用 Laravel 做一个小项目,现在我在 HTML 表中显示我在数据库中的产品。所以现在我创建了另一个名为 variables 的数据库表来存储产品variants,我想count the number of variants我有each product 这是我的代码:如您所见,我还选择了categories, brands, suppliers 我想计算的数量variants (因为我已经有一个名为的表variants,包含该product_id字段)public function index(){ $products = Product::with(['category', 'brand', 'supplier'])->orderBy('id', 'desc')->paginate(15); return response()->json($products);}
1 回答

江户川乱折腾
TA贡献1851条经验 获得超5个赞
我假设你的product表与 有很多关系variants。正如你在评论中所说products.id & variants.product_id
使用 hasMany 关系在产品模型中制作功能变体。
Class Product extends Model{
public function variants(){
return $this->hasMany('App\Variant','product_id','id');
}
}
现在你可以通过使用来调用它withCount
public function index()
{
$products = Product::with(['category', 'brand', 'supplier','variants'])->withCount('variants')->orderBy('id', 'desc')->paginate(15);
return response()->json($products);
}
因此,您也会得到product配合variants和计数。
- 1 回答
- 0 关注
- 157 浏览
添加回答
举报
0/150
提交
取消