You need to enable JavaScript to run this app. Laravel中有没有更优雅的方式获取嵌套关联数据?
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中有没有更优雅的方式获取嵌套关联数据?

业务场景

我目前对接的业务涉及三张数据表,对应结构如下:

  • products 表
    products表结构
  • shop 表
    shop表结构
  • users 表
    users表结构

表间关联关系:

  • products.shop_id 是 shop 表的外键
  • shop.shop_owner_id 是 users 表的外键

当前需求为:已知 product_id,直接获取对应的店铺店主ID(shop_owner_id)。目前能想到的实现方式:

方式1:拆分两步查询

  1. 通过 product_id 查询得到对应的 shop_id
  2. 用上一步的 shop_id 再查询得到 shop_owner_id

方式2:手写原生SQL,联表三张表后通过 product_id 直接查询目标字段

想知道 Laravel 框架内有没有更优雅的实现方式?


实现方案

Laravel 本身的模型关联、查询构造器完全可以覆盖这个需求,不需要手写原生SQL,也不需要拆成两步冗余查询,常见实现分三种场景,按需选择即可:

1. 常规模型关联写法

先把三个模型的基础关联关系配置好,后续调用可以直接链式取值,维护性极强:

第一步:配置模型关联

  • Product 模型(对应 products 表)定义和店铺的关联:
// app/Models/Product.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    // 单个商品归属单个店铺
    public function shop()
    {
        return $this->belongsTo(Shop::class, 'shop_id');
    }
}
  • Shop 模型(对应 shop 表)定义和店主的关联:
// app/Models/Shop.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Shop extends Model
{
    // 单个店铺归属单个店主
    public function owner()
    {
        return $this->belongsTo(User::class, 'shop_owner_id');
    }
}

第二步:业务代码调用

配置完关联后,不需要手动写联表逻辑,直接通过链式关联属性取值即可:

// 已知 product_id,直接查询对应店主ID
$shopOwnerId = Product::query()
    ->where('id', $productId)
    ->value('shop.owner.id');

Laravel 会自动处理关联查询逻辑,自动避免N+1查询问题,代码简洁易读。

2. 远层关联优化(高频场景推荐)

如果你的业务里经常需要从商品维度直接拿店主信息,可以在 Product 模型里配置 Laravel 提供的 hasOneThrough 远层一对一关联,把两层关联直接打通,调用更简短:

// 在 Product 模型中追加关联方法
public function shopOwner()
{
    return $this->hasOneThrough(
        User::class, // 最终要关联的目标模型(用户表)
        Shop::class, // 中间关联模型(店铺表)
        'id', // 中间表(shops)的外键,对应 products 表的 shop_id
        'id', // 目标表(users)的主键
        'shop_id', // 当前模型(products)的本地关联键
        'shop_owner_id' // 中间表(shops)的外键,对应 users 表的 id
    );
}

配置完之后调用会更直接:

$shopOwnerId = Product::findOrFail($productId)->shopOwner->id;

3. 高性能取值场景

如果你的业务只需要 shop_owner_id 这一个字段,不需要加载完整的模型实例,可以用查询构造器直接联表取值,性能更高:

$shopOwnerId = Product::where('id', $productId)
    ->join('shops', 'products.shop_id', '=', 'shops.id')
    ->value('shops.shop_owner_id');

这种写法和原生SQL性能一致,但不需要手动拼SQL语句,后续如果表关联字段调整,只需要改一处即可。


内容的提问来源于stack exchange,提问作者Abdus Sattar Bhuiyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.17 17:45:08