php - How to find data on pivot table of a Many To Many relationship
I have a Many To Many relationship between users
& wallets
.
So at the User.php
Model:
public function wallets()
{
return $this->belongsToMany(Wallet::class,'user_wallet','user_id','wallet_id')->withPivot('balance');
}
And at Wallet.php
Model:
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:
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:
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
.
So how can I define user_wallet
table for this where
condition?
I would really appreciate any idea or suggestion from you guys about this...
Thanks in advance.
Answer
Solution:
I think you can use 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');
}
Source