如何在laravel中编写此查询?

时间:2015-07-13 04:29:39

标签: laravel-5

我想获取最多3个未读特定用户的通知,并且他们的create_at日期低于或等于特定日期,我想要像bellow查询:

select count(*) as aggregate from 
(
   select * from `notifications` 
   where `notifications`.`user_id` = '20' and `notifications`.`user_id` is not    null and `is_read` = '0'
   and created_at <= '2015-07-12 11:41:10' limit 3
) AS src

请考虑以下问题:

$displayedNotifications = $user->notifications(function($query) use ($timestamps) {
                    return $query->Where('created_at', '<=', $timestamps);
                })->unread()->take(3)->count();

1 个答案:

答案 0 :(得分:1)

您好@jones必须将范围方法scopeUnread添加到Notification模型中:

function scopeUnread($query, $timestamp) {
  $query->where('is_read', false);

  if (! empty($timestamp) ) 
    $query->where('created_at', '<=', $timestamp);

  return $query;
}

现在您可以从User模型访问该范围,如下所示:

$user->notifications()->unread($timestamp);

$user->notifications()->unread($timestamp)->take(3)->count();

要播放未读通知。

希望它适合你