使用 Laravel Eloquent 进行选择和计数

我正在使用 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);

}


慕码人8056858
浏览 159回答 1
1回答

江户川乱折腾

我假设你的product表与 有很多关系variants。正如你在评论中所说products.id & variants.product_id使用 hasMany 关系在产品模型中制作功能变体。Class Product extends Model{    public function variants(){        return $this->hasMany('App\Variant','product_id','id');    }}现在你可以通过使用来调用它withCountpublic function index(){    $products = Product::with(['category', 'brand', 'supplier','variants'])->withCount('variants')->orderBy('id', 'desc')->paginate(15);    return response()->json($products);}因此,您也会得到product配合variants和计数。
打开App,查看更多内容
随时随地看视频慕课网APP