【问题标题】:Laravel - condition on with()Laravel - with() 条件
【发布时间】:2021-12-02 20:04:27
【问题描述】:

我想在 UserEnabledNotificationsNotificationTypesId 列上将表 NotificationTypesUserEnabledNotificationTypesId 联接,仅适用于 NotificationTypes 表的 deleted_at 列为空的行。我试过如下。但它不是对NotifocationTypes 表中deleted_at 列的null 值进行排序。有什么解决办法吗?

UserEnabledNotifications::with('userNotications', function ($query){
    $query->whereNull('deleted_at');
})->select('userId','notificationTypesId')->get();

UserEnabledNotifications

public function userNotifications(){
  return $this->belongsTo(NotificationTypes::class, 'notificationTypesId','id');
}

【问题讨论】:

  • 不需要写whereNull条件。对于 deleted_at laravel,它会自行将 deleted_at 是一个空条件附加到查询中。因此,请尝试不使用它。
  • @Vivek Pawar 在有或没有空条件的情况下都没有排序
  • 你想要orderby 的关系吗?
  • @Vivek Pawar 我只是想以任何方式实现我在原始问题中所说的话

标签: php laravel eloquent laravel-8 query-builder


【解决方案1】:

您需要将 with/closure 作为数组键/值对传递

UserEnabledNotifications::with(['userNotifications' => function ($query){
    $query->whereNull('deleted_at');
}])->select('userId','notificationTypesId')->get();

要仅获取具有未删除的 userNotifications 的 UserEnabledNotifications,您需要whereHas

UserEnabledNotifications::whereHas('userNotifications', function(Builder $query) {
    $query->whereNull('deleted_at');
})
    ->with(['userNotifications' => function($query) {
        $query->whereNull('deleted_at');
    }])->select('userId', 'notificationTypesId')->get();

【讨论】:

  • 我已经试过了。它也没有做我需要的排序
  • 您想要所有的 UserEnabledNotifications 都只包含未删除的 userNotifications,还是只想要包含未删除 userNotifications 的 UserEnabledNotifications?
  • 两者意思一样知道吗?你能解释一下你的问题吗?
  • 好吧,现在您将获得 所有 UserEnabledNotifications,然后是所有未删除的子 userNotifications。另一种选择是获取具有未删除的子 userNotifications 的 UserEnabledNotifications。请注意,这被认为是过滤,而不是排序(排序)
  • 看你的关系,with 上的子查询是不必要的。 whereHas 返回所有具有未删除 userNotifications 的 UserEnabledNotifications。如果它是一对多的关系,那么您可能有已删除的通知和一些未删除的通知,因此子查询将仅返回未删除的通知。由于它是 belongsTo 关系,因此是一对一的,因此不需要 with 上的子查询
【解决方案2】:

尝试使用此查询将列替换为实际列。无需检查deleted_atNULL 值。它会默认检查NULL

UserEnabledNotifications::with(['userNotifications', function ($query){
    $query->orderBy('column', 'ASC');
}])->select('userId','notificationTypesId')->get();

让我知道结果。

【讨论】:

  • 实际列的意思,你指的是哪一个?
  • 设置主键(id).
猜你喜欢
  • 1970-01-01
  • 2019-07-08
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 1970-01-01
  • 2016-01-03
  • 1970-01-01
  • 2020-04-21
相关资源
最近更新 更多