简体   繁体   中英

SQL query with leftJoin and as in Eloquent

    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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM