eloquent - Lumen/Laravel Eloquent - 按数据透视表中的属性过滤
问题描述
我有三个表,users
和talents
作为user_talent
数据透视表,我正在尝试根据用户的才能过滤用户。关系是用户可以拥有多个人才,人才可以分配给多个用户。
关系:
public function talents() {
return $this->belongsToMany('App\Models\Talent');
}
public function users() {
return $this->belongsToMany('App\Models\User');
}
这运作良好。现在我正在尝试根据人才 ID 过滤用户,但我没有这样做。
With: Talent 模型不使用 $with,而 User 使用:
protected $with = [
'talents'
];
过滤器(请注意我删除了其他过滤器和分页器):
public function getAllModelsWithFilters(Request $request) {
$model = User::query();
$sortColumn = 'full_name';
$sortDir = 'orderBy';
if ($request->has('talents')) {
$ids = [];
$array = explode(',', $request->query('talents')); // provided as string: 1,2,3,6
foreach($array as $arr) {
$res = (int) $arr;
if (!empty($res)) {
$ids[] = $res;
}
}
if (!empty($ids)) {
$model->with([
'talents' => function ($q) use ($ids) {
$q->whereIn('talents.id', $ids);
}
]);
}
}
return CustomResponse::success([
'data' => $model->{$sortDir}($sortColumn)->get()
]);
}
结果
结果是我找回了所有用户,即使是那些没有分配才能的用户。
预期成绩
根据人才筛选的用户集合。
使用流明 v7.1.3
解决方案
在这里得到答案:laravel belongsToMany 过滤器
将上面的代码更改为:
if ($request->has('talents')) {
$ids = [];
$array = explode(',', $request->query('talents')); // provided as string: 1,2,3,6
foreach($array as $arr) {
$res = (int) $arr;
if (!empty($res)) {
$ids[] = $res;
}
}
if (!empty($ids)) {
$model->whereHas('talents', function($q) use ($ids) {
$q->whereIn('talents.id', $ids);
});
}
}
推荐阅读
- python - 为什么 Tkinter Scrolledtext 小部件在我的情况下会忽略空格?
- xslt - Datapower_Remove 除 SOAP 到 JSONX XSLT 中的一个以外的所有 Null 元素
- node.js - 无法从异步函数中提取结果,即使它已显示
- php - 如何使用 php 读取一些文件部分
- python - 如何将我的 Tkinter 条目的数据存储到 DataFrame 中,以便以后将其导出到 Excel?
- r - R:将大型数据帧转换为成对相关矩阵
- python - 如何让我的游戏中的零食出现随机颜色?
- java - JPA WrongArgumentException:SQL 字符串不能为 NULL:尽管 CrudRepository 保存函数接收填充的实体
- r - 绘制 geom_line() + geom_point() R
- javascript - 为什么在我的 jQuery 循环中返回不起作用?