jones
jones

Reputation: 1453

How to write this query in laravel?

I want to take maximum 3 notification of specific user that are unread and also their create_at date is lower than or equal to specific date, i want something like bellow query:

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

just pleas consider bellow query:

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

Upvotes: 0

Views: 49

Answers (1)

absolux
absolux

Reputation: 323

Hi @jones you have to add a scope method scopeUnread to Notification model as :

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

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

  return $query;
}

now you can access that scope from User model like below:

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

and

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

To have unread notifications count.

Hope it works for you

Upvotes: 1

Related Questions