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

如何使用Laravel Eloquent获取嵌套关联的特定用户订单数据?

获取特定用户名下所有Marketplace的订单(Laravel Eloquent实现)

你可以通过以下几种方式用Eloquent实现需求:

方法一:定义跨表关联(推荐)

直接在User模型中新增一个关联,利用hasManyThrough配合多态条件直接关联订单:

// 在User模型中添加该方法
public function marketplaceOrders()
{
    return $this->hasManyThrough(
        Order::class,
        Marketplace::class,
        null, // 多对多关联的中间表会自动处理,此处留空即可
        'orderable_id', // orders表关联marketplaces的外键
        'id', // users表主键
        'id' // marketplaces表主键
    )->where('orderable_type', Marketplace::class); // 指定多态关联类型
}

使用时直接调用关联获取:

$userId = 1; // 替换为实际用户ID
// 获取用户所有订单
$orders = User::find($userId)->marketplaceOrders;
// 可追加查询条件
$orders = User::find($userId)->marketplaceOrders()->where('status', 'completed')->get();

方法二:通过关联嵌套查询

如果不想新增模型关联,直接用whereHas嵌套筛选属于该用户市场的订单:

$userId = 1;
$orders = Order::where('orderable_type', Marketplace::class)
    ->whereHas('orderable', function ($query) use ($userId) {
        $query->whereIn('id', function ($subQuery) use ($userId) {
            $subQuery->select('marketplaces.id')
                ->from('marketplaces')
                ->join('marketplace_user', 'marketplaces.id', '=', 'marketplace_user.marketplace_id')
                ->where('marketplace_user.user_id', $userId);
        });
    })->get();

方法三:加载关联后合并数据

这种方式更直观,但数据量较大时性能不如直接数据库查询:

$userId = 1;
// 预加载用户的所有市场及对应订单
$user = User::with('marketplaces.orders')->find($userId);
// 合并所有市场的订单
$orders = collect();
foreach ($user->marketplaces as $marketplace) {
    $orders = $orders->merge($marketplace->orders);
}
// 可选:对订单去重
$orders = $orders->unique('id')->values();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 18:35:24