【问题标题】:php - Laravel - filter relation data inside relationphp - Laravel - 过滤关系内的关系数据
【发布时间】:2017-11-28 16:34:14
【问题描述】:

我正在尝试使用 usercalendars 检索 Player - 播放器 hasOne 用户和播放器 hasMany 日历。 但我只需要男性用户 - 工作正常,然后我必须检查日历冲突 - 只选择没有日历冲突的玩家,查询:

$freeplayers = Player::whereNotIn('id', $playersev)
                         ->with('user','calendars')
                         ->whereHas('user', function ($query) {
                            $query->where('gender', 'male');
                         })
                         ->whereHas('calendars', function ($query) use ($event) {
                             $query->whereNotIn('fulldate', $event->fulldate);
                         })
                         ->get();

第二个whereHas 不起作用,因为:

  • 并非每个玩家都有日历中的事件(所以我无法访问fulldate attr)
  • 播放器hasMany 日历,所以它作为另一个集合返回,我必须在这个日历集合的每个项目中运行->whereNotIn(......

所以,我需要日历为空的男性玩家(他们可用)和现有日历中没有冲突的玩家。

我怎样才能做到这一点?我尝试合并 ->doesntHave('calendars')->orWhereHas('cale... 但它不起作用,因为如果用户有日历,它会作为另一个集合返回...

谢谢

【问题讨论】:

  • 你能显示 fullDate 是什么吗?
  • @NiRR - 只是普通的日期时间,例如2017-11-10 16:00:00

标签: php laravel laravel-5 laravel-5.5


【解决方案1】:

构建器的完整API,使用https://laravel.com/api/5.2/Illuminate/Database/Eloquent/Builder.html

您需要执行“子查询”,因为您希望发生以下情况之一: 日历为空或日历日期不是特定日期。

所以

Player::where(function($query) use ($forbiddenDatesArray) {
    $query->has('calendars', 0)
          ->orWhereHas('calendars', function($query) use ($forbiddenDatesArray){
              $query->whereNotIn('fullDate', $forbiddenDatesArray);
          });
});

【讨论】:

  • 完美!它有效,谢谢,只是小错字 - 日历不是日历:)
【解决方案2】:

whereNotIn 检查给定数组的值作为第二个参数

试试

->whereHas('calendars', function ($query) use ($event) {
    $query->where('fulldate', '!=', $event->fulldate);
})

更新:获取没有日历条目的玩家

->whereHas('calendars', function ($query) use ($event) {
    $query->where('fulldate', '!=', $event->fulldate)
          ->orWhere('fulldate', null);
})

【讨论】:

  • 谢谢,现在可以进行日期检查,但不包括没有日历的玩家
  • 太棒了!乐意效劳。如果有帮助,请接受答案。
  • 好吧,我也需要没有日历的玩家:)
  • 为没有日历的玩家更新了答案。
  • 这将只返回有日历的玩家,如果玩家没有日历,则没有 fulldate 属性,整个日历对象为空。 NiRR 的解决方案有效
猜你喜欢
  • 2021-08-07
  • 2019-07-24
  • 2021-03-09
  • 2020-12-17
  • 2016-10-15
  • 2018-05-20
  • 1970-01-01
  • 2017-08-11
  • 2020-11-22
相关资源
最近更新 更多