Search code examples
phplaraveleloquenteloquent-relationship

Laravel eloquent update column using relationship column


How can achieve this query?

Sale::with(['catalog'])
    ->whereIn('id', $ids)
    ->update(['price' => DB::raw('catalog.price')]);

This is not working, it shows undefined table... I tried to put the name of the table but it's the same.

On the internet I always found the easy query:

Sale::with(['catalog'])
    ->whereIn('id', $ids)
    ->update(['price' => 5]);

Okay! When I want to update all rows with the same value is easy, in addition is easy when you want to update with a column of the same table like:

Sale::with(['catalog'])
    ->whereIn('id', $ids)
    ->update(['price' => DB::raw('price_alternative')]);

But how about using a column of another table with a relationship? I haven't found the solution.

I know this can be solved using entire raw query, but I wanted to know if it can be achieved by the eloquent way


Solution

  • You probably need to join in the catalog table on your querybuilder. This is different than using with(). Something along the lines of

    Sale::whereIn('id', $ids)
        ->join('catalog', 'sales.catalog_id', '=', 'catalog.id')
        ->update(['price' => DB::raw('catalog.price')]);