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

Laravel Eloquent是否有内置关联实现同外键关联查询?

Laravel Eloquent 实现 Invoice 关联用户 PaymentMethod 的方案

Laravel Eloquent 没有专门针对该场景的原生关联类型,但可以通过两种优雅的方式实现需求,无需手动编写 JOIN 语句:

方法一:通过 User 模型间接关联(最直观)

利用已有的 Invoice -> User 和 User -> PaymentMethod 关联,间接获取支付方式:

模型关联定义

// Invoice.php
public function user()
{
    return $this->belongsTo(User::class);
}

// User.php
public function paymentMethods()
{
    return $this->hasMany(PaymentMethod::class);
}

使用方式

$invoice = Invoice::find($invoiceId);
$userPaymentMethods = $invoice->user->paymentMethods;

方法二:用 hasManyThrough 直接关联(更便捷)

你之前误解了 hasManyThrough 的适用场景,其实它完全可以处理这种「当前模型 -> 中间模型 -> 目标模型」的关联结构,只需正确配置参数:

模型关联定义

// Invoice.php
public function paymentMethods()
{
    return $this->hasManyThrough(
        PaymentMethod::class, // 目标模型
        User::class, // 中间模型
        'id', // 中间模型(User)的关联键,对应 Invoice 的 user_id
        'user_id', // 目标模型(PaymentMethod)的外键,对应 User 的 id
        'user_id', // 当前模型(Invoice)的外键
        'id' // 中间模型(User)的主键
    );
}

使用方式

直接通过 Invoice 模型获取关联的支付方式:

$invoice = Invoice::find($invoiceId);
$userPaymentMethods = $invoice->paymentMethods;
// 支持链式调用查询构造器方法
$filteredMethods = $invoice->paymentMethods()->where('type', 'credit_card')->get();

补充:自定义查询关联

如果不想用 hasManyThrough,也可以在 Invoice 模型中定义一个返回查询构造器的方法:

// Invoice.php
public function paymentMethods()
{
    return PaymentMethod::where('user_id', $this->user_id);
}

使用时需要调用 get() 执行查询:

$userPaymentMethods = $invoice->paymentMethods()->get();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 19:00:00