【发布时间】: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