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

Laravel5.8中基于多对多关联查询用户关联钱包及中间表数据的方法

解决方案

步骤1:修正多对多关联定义

你的中间表包含额外的balance字段,且User模型主键自定义为usr_id,需要调整关联方法声明额外需要读取的中间表字段:

User.php 调整后代码

public function wallets()
{
    // 参数说明:关联模型、中间表名、当前模型在中间表的外键、关联模型在中间表的外键
    return $this->belongsToMany(Wallet::class, 'user_wallet', 'user_id', 'wallet_id')
        // 声明需要读取的中间表字段
        ->withPivot('balance', 'created_at', 'updated_at');
}

补充注意

请确认你的User模型已经声明自定义主键,否则路由隐式绑定会失效:

// User模型内添加
protected $primaryKey = 'usr_id';

步骤2:控制器中读取关联数据

直接使用关联预加载即可拿到用户关联的所有钱包+中间表数据:

public function index(User $user)
{
    // 预加载钱包关联,避免N+1查询问题
    $user->load('wallets');
    return view('admin.wallets.user.index', compact('user'));
}

步骤3:Blade模板中使用中间表数据

遍历关联数据时,通过pivot属性访问中间表字段:

@foreach($user->wallets as $wallet)
<div class="wallet-item">
    <p>钱包名称:{{ $wallet->title }}</p>
    <p>钱包标识:{{ $wallet->name }}</p>
    <!-- 中间表balance字段通过pivot读取 -->
    <p>当前余额:{{ $wallet->pivot->balance }}</p>
    <p>绑定时间:{{ $wallet->pivot->created_at->format('Y-m-d H:i') }}</p>
</div>
@endforeach

可选方案:直接查询中间表

如果不需要关联Wallet表的字段,也可以直接用查询构造器读取中间表:

use Illuminate\Support\Facades\DB;

public function index(User $user)
{
    $userWallets = DB::table('user_wallet')
        ->where('user_id', $user->usr_id)
        ->get();
    return view('admin.wallets.user.index', compact('user', 'userWallets'));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 05:42:03