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

将MySQL原生查询转换为Laravel 5.5 Eloquent ORM

转换Laravel 5.5 Eloquent写法方案

没问题,我来帮你把这段原生MySQL查询转换成Laravel 5.5的Eloquent写法,顺便拆解下对应逻辑:

完全匹配原查询的Eloquent写法

这段写法严格对应你原查询的INNER JOIN和聚合统计逻辑:

use App\Models\Item; // 记得引入你的Item模型
use Illuminate\Support\Facades\DB;

$categoryItemCounts = Item::select('items.category_id', DB::raw('count(items.id) as count'))
    ->join('item_categories as c', 'c.id', '=', 'items.category_id')
    ->groupBy('items.category_id')
    ->get();

代码对应原查询的说明:

  • Item::select(...) 对应原生SQL的SELECT子句,用DB::raw()包裹聚合函数count(items.id) as count,避免Eloquent自动转义导致语法错误。
  • ->join(...) 对应原生的INNER JOIN,参数依次是关联表名(带别名)、关联匹配条件。
  • ->groupBy('items.category_id') 完全复刻原查询的GROUP BY分组逻辑。
  • ->get() 执行查询并返回包含结果的Eloquent集合,你可以直接遍历这个集合获取每个分类的ID和对应商品数量。

更简洁的关联写法(可选)

如果你的Item模型已经和ItemCategory模型定义了关联关系,可以用更优雅的方式实现类似效果(注意:这是LEFT JOIN逻辑,会返回所有分类,无商品的分类count为0,和原查询的INNER JOIN略有区别):

首先在Item模型中定义关联:

// app/Models/Item.php
public function category()
{
    return $this->belongsTo(ItemCategory::class, 'category_id');
}

然后在ItemCategory模型中定义反向关联:

// app/Models/ItemCategory.php
public function items()
{
    return $this->hasMany(Item::class, 'category_id');
}

之后就可以用withCount快速获取每个分类的商品数量:

use App\Models\ItemCategory;

$categoriesWithCount = ItemCategory::withCount('items')->get();
// 访问方式:$category->items_count

内容的提问来源于stack exchange,提问作者Moiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 09:19:12