简体   繁体   中英

Laravel - Copy collection data to another table and delete

I want to delete entries which are older than 3 days and move them to another (archive) table.

So far I do it like this:

public function handle() {
    $route = Route::where('created_at', '<=', Carbon::now()->subDays(3))->get();
    $routeCopy = $route;
    $route = Route::where('created_at', '<=', Carbon::now()->subDays(3))->delete();

    foreach ($routeCopy as $r) {
        $routeArchive = new RouteArchive();
        $routeArchive->id = $r->id;
        $routeArchive->startLocation = $r->startLocation;
        $routeArchive->endLocation = $r->endLocation;
        $routeArchive->save();
    }

}

Is there a way to avoid double querying in this case? Btw Route and RouteArchive are not same. Route contains many other columns including id, startLocation, endLocation ... RouteArchive contains only id, startLocation and endLocation .

Assuming that you have a primary key set up on the route table, you should be able to do something like this

public function handle() {
    $route = Route::where('created_at', '<=', Carbon::now()->subDays(3))->get();
//    $routes = $route;
 //   $route = Route::where('created_at', '<=', Carbon::now()->subDays(3))->delete();

    foreach ($route as $r) {
        $routeArchive = new RouteArchive();
        $routeArchive->id = $r->id;
        $routeArchive->startLocation = $r->startLocation;
        $routeArchive->endLocation = $r->endLocation;
        $routeArchive->save();

        $r->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