Laravel多模型查询咨询:根据URL匹配统计有效商品数量
代码功能与实现
预期实现功能
- 获取当前路由的URL
- 从Section、Category、Brand三个模型中,分别根据URL查询对应的记录ID
- 根据匹配到的ID,查询Product模型中状态为1的商品详情并统计数量;若没有匹配到任何ID,数量设为0
实现代码
// 获取当前路由URL $url = Route::getFacadeRoot()->current()->uri(); // 从各模型中查询对应URL的记录ID $sectionID = Section::select('id', 'url')->where('url', $url)->first()->toArray(); $categoryID = Category::select('id', 'url')->where('url', $url)->first()->toArray(); $brandID = Brand::select('id', 'url')->where('url', $url)->first()->toArray(); // 根据匹配到的ID查询商品并统计数量 if (array_key_exists("id", $sectionID)) { $productDetails = Product::where(['status' => 1, 'sections_id' => $sectionID['id']])->first()->toArray(); $totalCountProduct = count($productDetails); } else if (array_key_exists("id", $categoryID)) { $productDetails = Product::where(['status' => 1, 'categories_id' => $categoryID['id']])->first()->toArray(); $totalCountProduct = count($productDetails); } else if (array_key_exists("id", $brandID)) { $productDetails = Product::where(['status' => 1, 'brands_id' => $brandID['id']])->first()->toArray(); $totalCountProduct = count($productDetails); } else { $totalCountProduct = 0; }
注:当前代码存在潜在问题:若
first()未查询到记录时,调用toArray()会抛出错误,建议先判断查询结果是否存在再进行后续操作。
内容的提问来源于stack exchange,提问作者Sudhir Raj
相关产品推荐
相关产品推荐

