【问题标题】:Query on Pivot relation查询枢轴关系
【发布时间】: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 关系。

标签: php laravel


【解决方案1】:

(Laravel 产品模型) 公共功能 products() { 返回 $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; }

【讨论】:

    猜你喜欢
    • 2019-07-05
    • 1970-01-01
    • 2018-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-23
    • 2019-07-27
    相关资源
    最近更新 更多