[英]How to find data on pivot table of a Many To Many relationship
I have a Many To Many relationship between users
& wallets
.我在
users
和wallets
之间有一个多对多的关系。
So at the User.php
Model:所以在
User.php
模型中:
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}
And at Wallet.php
Model:在
Wallet.php
模型中:
public function users()
{
return $this->belongsToMany(User::class,'user_wallet','user_id','wallet_id');
}
And also the table Migration of user_wallet
also goes here:还有
user_wallet
的表迁移也放在这里:
public function up()
{
Schema::create('user_wallet', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('usr_id')->on('users');
$table->unsignedBigInteger('wallet_id');
$table->foreign('wallet_id')->references('id')->on('wallets');
$table->integer('balance');
$table->timestamps();
});
}
Now I need to return a data based on it's User Id & Wallet Id, like this:现在我需要根据它的用户 ID 和钱包 ID 返回一个数据,如下所示:
And at the Controller:在控制器处:
$bal = Wallet::where(['user_id' => $user_id, 'wallet_id' => $wallet_id]);
But this is wrong because the Model Wallet
is connected to wallets
table and not the pivot table which is user_wallet
.但这是错误的,因为模型
Wallet
连接到wallets
表而不是user_wallet
数据透视表。
So how can I define user_wallet
table for this where
condition?那么如何为这个
where
条件定义user_wallet
表呢?
I would really appreciate any idea or suggestion from you guys about this...我真的很感激你们对此的任何想法或建议......
Thanks in advance.提前致谢。
I think you can use whereHas我想你可以使用 whereHas
Wallet::with("users")->whereHas('users',function ($query)use($user_id){
$query->where('user_id',$user_id);
})->find($wallet_id)
or或者
Wallet::with("users")->whereHas('users',function ($query)use($user_id,$wallet_id){
$query->where('user_id',$user_id);
$query->where('wallet_id',$wallet_id);
})->first()
And also relationship need to be updated in wallet model并且还需要在钱包模型中更新关系
public function users() {
return $this->belongsToMany(User::class,'user_wallet','wallet_id','user_id');
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.