Laravel:是否可以在hasMany()上应用-> where()?

时间:2019-04-10 13:34:41

标签: php laravel orm

我有这个notifications表,其中有一个status列。除其他外,状态可能是“ ack”和“ noack”。因此,通知属于用户。如果要使用ORM查看用户的通知,可以在用户模型中使用hasMany(),例如:

public function notificaciones()
{
  return $this->hasMany('App\Notification', 'dest_id', 'id');
}

这很好用。 (dest_id表示通知是针对谁的,还有另一个origin_id可以告诉谁是导致通知的原因,无论如何,这都是有效的)

现在,我只想查看未确认(noack)的通知,我在想:

public function notificaciones()
{
  return $this->hasMany('App\Notificacion', 'dest_id', 'id')
                  ->where('status', 'noack');
}

但这会产生一个空集合。

这怎么实现?

1 个答案:

答案 0 :(得分:4)

您可以做类似的事情,

您在同一模型中创建一个新函数,并以获取noack通知为条件调用该核心方法。

public function noack_notifications() {
    return $this->notificaciones()->where('status','=', 'noack');
}

当您通过控制器使用find调用此方法时。

$user =  User::find($id);
dd($user->noack_notifications()->get());

这应该可以解决您的问题。

相关问题