【发布时间】:2021-09-23 03:47:55
【问题描述】:
我在用户模型和钱包模型之间有多对多关系:
Wallet.php:
public function users() {
return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
}
和User.php:
public function wallets() {
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');;
}
然后在 Blade,我尝试了这个:
@forelse($user->wallets as $wallet)
<tr>
<td>{{ $wallet->name }}</td>
<td>{{ $wallet->pivot->balance }}</td>
<td><a href="{{ route('user.WalletTransaction', ['walletId'=>$wallet->id,'userId'=>$wallet->users()->id]) }}" class="fa fa-exchange text-dark mt-1"></a></td>
</tr>
@empty
<td colspan="5" class="text-center">No wallet exist</td>
@endforelse
如您所见,我传递了两个参数作为路由名称user.WalletTransaction,这是一个链接:
{{ route('user.WalletTransaction', ['walletId'=>$wallet->id,'userId'=>$wallet->users()->usr_id]) }}
在 web.php 上:
Route::get('wallet/transaction/{wallet}/{user}', 'Wallet\UserWalletController@WalletTransaction')->name('user.WalletTransaction');
但它显示了这个错误:
未定义属性:Illuminate\Database\Eloquent\Relations\BelongsToMany::$usr_id
但是usr_id 是users 表中用户的ID:
数据透视表结构user_wallet 如下所示:
那么我怎样才能正确地将用户 ID 添加到该链接?
我非常感谢你们对此提出的任何想法或建议......
谢谢。
更新 #1:
<a href="{{ route('user.WalletTransaction', ['walletId'=>$wallet->id,'userId'=>$user->id]) }}" class="fa fa-exchange text-dark mt-1" /> 的结果显示两个链接!
【问题讨论】:
-
好吧,你的钱包“属于许多”用户,所以你想用
wallet->users()->usr_id访问哪个用户,wallet->users()有很多用户,这就是我猜它不起作用的原因。
标签: php laravel laravel-5.8