How to set values in one column table by values of column in another? [closed]

I have two tables:

------------
| reports  |
------------
| id       |
| date     |
------------

-------------
| orders    |
-------------
| id        |
| report_id |
| old_date  |
-------------

I want to do something like this:

foreach ($orders as $order) {
    $report = Report::findOrFail($order->report_id);
    $order->old_date = $report->date;
    $order->save();
}

I want to do not get all() orders and actions in foreach(), is it possible? (Using Laravel DB)

Code result must be the same as in the example, but the way must be using SQL queries to make all actions on the DB side.

Answer

Yes, it’s totally possible. But it’s bad practice to use foreach or any loop for this. Especially when you are selecting rows using all().

What if row counts ecxeeds to 1k? 10k? 1M?

You can use Structured Query Language (SQL) to get this done, Laravel DB maps parts of it (see Database: Query Builder):

Order::join('reports', 'reports.id', '=', 'orders.report_id')
  ->update([
    'orders.old_date' => DB::raw("reports.date")
  ]);

If you want to use Models & Loop for this than your code is totally right