【问题标题】:Laravel, How to retrieve parent records with certain Pivot table values belongsToManyLaravel,如何检索具有某些数据透视表值的父记录belongsToMany
【发布时间】:2018-03-28 20:51:31
【问题描述】:

如何根据数据透视表中的特定 ID 检索模型的所有记录?

我有以下 3 个表

用户; ID, 名字

统计; ID, 名字

stats_selected; 用户身份, stats_id

型号

用户.php

public function stats()
{
            return $this->belongsToMany('App\stats', 'stats_selected', 'user_id', 'stats_id')->withTimestamps();
}

控制器

        // Get all users with example of stats ID's
        $aFilterWithStatsIDs = [1,10,13];

        $oUser = User::with(['stats' => function ($query) use($aFilterWithStatsIDs ) {
                    $query->whereIn('stats_id', $aFilterWithStatsIDs);
                }])
                ->orderBy('name', 'desc')
                ->get()

这只会输出所有用户。顺便说一句,用那里的统计数据获取用户并将这些选定的统计数据保存到数据库中不是问题。这适用于上述行。

但我如何仅检索具有特定 stats_id 的用户?

【问题讨论】:

    标签: laravel many-to-many has-and-belongs-to-many


    【解决方案1】:

    但是我如何只检索其中包含某些 stats_id 的用户呢?

    使用whereHas 条件。

    User::whereHas('stats', function ($stats) use ($aFilterWithStatsIDs) {
        $stats->whereIn('id', $aFilterWithStatsIDs);
    });
    

    【讨论】:

      猜你喜欢
      • 2018-09-26
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2017-06-04
      • 2022-11-28
      • 2019-08-19
      相关资源
      最近更新 更多