首页 > 解决方案 > 查询枢轴关系

问题描述

我想使用 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()

有没有办法做到这一点?

标签: phplaravel

解决方案


(产品模型 Laravel) public function products() { return $this->belongsToMany('App\Product'); } (Shop Model Laravel)public function shop(){ return $this->belongsToMany('App\Shop');} 你可以指定数据透视表的实际字段名 public function products(){ return $this->belongsToMany ('App\Product','products_shops', 'shops_id', 'products_id');}在我们的循环中获取这些值的可能性 foreach ($shop-products as $product){echo $product->pivot->price; }


推荐阅读