Reputation: 10182
DELETE a
FROM notifications a
LEFT JOIN
(SELECT ID
FROM notifications
WHERE to_user_id = 1
ORDER BY ID DESC
LIMIT 100) b ON a.ID = b.ID
WHERE b.ID IS NULL
AND a.to_user_id = 1
I am trying to convert this SQL to laravel eloquent
So far I tried
Notifications::from("notifications as a")
->leftJoin('notifications as b', function($query) {
$query->select("ID")
->from("notifications")
->where("to_user_id", 1)
->orderBy("ID", "DESC")
->limit(100);
})->whereNull("b.ID")->where("a.to_user_id",1)->delete();
But I can't get it to works. Any idea?
Upvotes: 1
Views: 48
Reputation: 17216
So you want to delete all the notifications received by a user except the last 100 ones. would it not be simpler to select the time/id of the 100th notification and delete the notification under that value?
$lastNotificationId = $user->notifications()
->limit(1) //you can skip this one => the method 'value()' does a limit(1) auto
->offset(99)
->orderBy('id','DESC')
->value('id');
if ($lastNotificationId) { //in case the user has less than 100 notifications
$user->notifications()
->where('id', '<', $lastNotificationId )
->delete();
}
Upvotes: 1