John Davidson

php - Query on Pivot relation

0 comments
Message:


I would like to query pivot model relation using Eloquent.


I've my User model :


class User extends Authenticatable
{
public function preferences(): BelongsToMany
{
return $this->belongsToMany(Preference::class, 'user_preference')
->using(UserNotificationPreference::class) //Custom Pivot model
->withPivot([enabled, channel_id]);
}
}

Here is the custom pivot model :


class UserNotificationPreference extends Pivot
{

/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'enabled' => 'boolean'
];

/**
* Channel relation.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function channel(): BelongsTo
{
return $this->belongsTo(Channel::class);
}
}

And the preference model :


class Preference extends Model
{
// protected $connection = "apodis";

/**
* The users that belong to the preference.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function users(): BelongsToMany
{
return $this->belongsToMany(Preference::class, 'user_channel_notification_preference')
->using(UserNotificationPreference::class) //custom pivot
->withPivot(['preference_id', 'user_id', 'enabled', 'channel_id']);
}
}

From a User model, i would like to retrieve Preferences after querying custom pivot table relationship (Channel::class) ,
something like :


$user->preferences()
->wherePivot('enabled', true)
->whereHasPivot('channel', function(Builder $query) {
//doesn't exists
})->get()

There is a way to achieve this ?



My Answer:
Yes, you can achieve this by using the `whereHasPivot` method in your query. Here's how you can modify your query to include the Channel relation:

php
$user->preferences()
->wherePivot('enabled', true)
->whereHasPivot('channel', function($query) {
$query->where('name', 'your_channel_name');
})->get();


In the `whereHasPivot` method, you can specify the conditions for the Channel relation. In this example, I used `name` as an example column in the Channel table. You can replace it with the actual column name you want to query on.

This will retrieve the Preferences for the User where the pivot table has the enabled column set to true and the Channel relation meets the specified conditions.

Rate this post

5 of 5 based on 9029 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us