我在用户和钱包模型之间存在多对多关系:
Wallet.php
:
public function users()
{
return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id')->withPivot('balance');
}
User.php
:
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}
数据透视表user_wallet
是这样的:
然后在控制器上,我需要访问该balance
字段:
public function chargeWallet(Request $request, $wallet, $user)
{
// $wallet is wallet_id (2) & $user is user_id (373)
$bal = Wallet::with("users")
->whereHas('users', function ($query) use ($user) {
$query->where('id',$user);
})->where('id', $wallet)->first();
dd($bal->balance);
}
但现在我得到null
了dd($bal->balance)
!!
那么这里有什么问题呢?我怎样才能正确获得balance
?