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

Laravel Eloquent三表关联查询:无法获取分类名称

解决Laravel Eloquent三表关联获取分类名称的问题

我明白你现在的困扰——三表关联的场景比常见的一对一/一对多要绕一点,不过按照Laravel Eloquent的关联逻辑,其实很容易解决。咱们一步步来:

1. 先确认模型的关联关系

首先要在对应的模型里正确定义关联,因为你的关联字段不是Laravel默认的xxx_id格式(比如用了item_code而不是item_id),所以需要明确指定关联字段:

Item 模型(app/Models/Item.php)

class Item extends Model
{
    // 关联到多个Attribute
    public function attributes()
    {
        // 参数依次是:关联模型,关联表的外键,当前模型的关联字段
        return $this->hasMany(Attribute::class, 'item_code', 'item_code');
    }
}

Attribute 模型(app/Models/Attribute.php)

class Attribute extends Model
{
    // 关联到所属的Category
    public function category()
    {
        // 参数依次是:关联模型,当前表的外键,关联模型的主键
        return $this->belongsTo(Category::class, 'category_id', 'id');
        // 如果你的字段是默认的`category_id`和`id`,可以省略后面两个参数,但明确写出来更清晰
    }
}

2. 使用嵌套预加载获取分类数据

你之前的代码只预加载了attributes,现在需要嵌套预加载它关联的category,这样就能一次性把所有需要的数据都查出来(避免N+1查询问题):

$items = Item::with('attributes.category')->paginate(15);

之后你就可以在视图或者逻辑里直接访问分类名称了,比如:

@foreach($items as $item)
    <div class="item">
        <h4>商品: {{ $item->name }}</h4>
        @foreach($item->attributes as $attr)
            <p>属性: {{ $attr->attr_name }} | 分类: {{ $attr->category->name }}</p>
        @endforeach
    </div>
@endforeach

3. 可选:用原生连表查询的方式(类似你提到的MySQL语句)

如果你更习惯用原生SQL的join写法,也可以这样实现,不过要注意一个商品对应多个属性时会出现重复记录,可能需要根据需求调整:

$items = Item::select(
        'items.*',
        'attributes.*',
        'categories.name as category_name'
    )
    ->join('attributes', 'items.item_code', '=', 'attributes.item_code')
    ->join('categories', 'attributes.category_id', '=', 'categories.id')
    ->paginate(15);

这种方式下,分类名称会直接作为category_name字段出现在结果里,不过如果一个商品有多个属性,会返回多条相同商品的记录,你可能需要用groupBy或者distinct来处理,或者根据业务需求调整查询条件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 09:44:19