You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 00:45:51