【发布时间】:2021-11-22 21:57:34
【问题描述】:
我想使用 Eloquent 查询数据透视模型关系。
我有我的用户模型:
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]);
}
}
这是自定义枢轴模型:
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);
}
}
以及偏好模型:
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']);
}
}
从用户模型中,我想在查询自定义数据透视表关系 (Channel::class) 后检索首选项, 类似:
$user->preferences()
->wherePivot('enabled', true)
->whereHasPivot('channel', function(Builder $query) {
//doesn't exists
})->get()
有没有办法做到这一点?
【问题讨论】:
-
一种选择是与枢轴模型本身建立
hasMany关系。