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

Laravel Eloquent如何从外键关联表获取指定字段值

场景1:DailyEarning 与 TradeLicence 存在关联关系

假设DailyEarning模型中已经定义了指向TradeLicence的关联方法tradeLicence(),示例如下:

// DailyEarning Model 中的关联定义
public function tradeLicence()
{
    return $this->belongsTo(TradeLicence::class);
}

你在DailyEarningController的show()方法里可以用预加载嵌套关联的方式获取数据,避免N+1查询问题:

public function show(DailyEarning $dailyEarning)
{
    // 预加载关联的TradeLicence,以及TradeLicence对应的分类数据,仅查询需要的字段优化性能
    $dailyEarning->load([
        'tradeLicence' => function($query) {
            $query->select('id', 'category_id', 'created_at', 'updated_at');
        },
        'tradeLicence.businessCategories' => function($query) {
            $query->select('id', 'fees');
        }
    ]);

    // 直接通过属性取值即可
    $fees = $dailyEarning->tradeLicence->businessCategories->fees;
    $licenceCreatedAt = $dailyEarning->tradeLicence->created_at;
    $licenceUpdatedAt = $dailyEarning->tradeLicence->updated_at;

    return view('daily_earning.show', compact('dailyEarning', 'fees', 'licenceCreatedAt', 'licenceUpdatedAt'));
}

场景2:不需要关联DailyEarning,直接获取所有TradeLicence对应数据

如果你的show方法需要展示所有TradeLicence的相关数据,直接查询TradeLicence模型即可:

// 预加载分类数据,只查询需要的字段
$tradeLicences = TradeLicence::with('businessCategories:id,fees')
    ->select('id', 'created_at', 'updated_at', 'category_id')
    ->get();

// 遍历取值示例
foreach ($tradeLicences as $licence) {
    $fees = $licence->businessCategories->fees;
    $createdAt = $licence->created_at;
    $updatedAt = $licence->updated_at;
}

可选优化建议

你当前TradeLicence模型里的关联是belongsTo单对一关系,方法名用复数businessCategories不符合Laravel命名规范,建议改成单数businessCategory,后续调用更符合直觉:

// TradeLicence Model 调整后
public function businessCategory()
{
    return $this->belongsTo(BusinessCategory::class,'category_id','id');
}
// 调整后取值方式变成 $licence->businessCategory->fees

无嵌套直接取值方案

如果你想要直接把fees拼到查询结果中不用嵌套访问,可以用join查询:

$tradeLicences = TradeLicence::join('business_categories', 'trade_licences.category_id', '=', 'business_categories.id')
    ->select('trade_licences.created_at', 'trade_licences.updated_at', 'business_categories.fees')
    ->get();
// 直接取 $licence->fees 即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 20:48:01