2015-07-13 120 views
0

我想利用未读以及他们create_at日期是低于或等于特定日期的特定用户的最大3通知,我想是这样波纹管查询:如何在laravel中写入此查询?

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

嗨@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(); 

为未读的通知数。

希望它适合你