Skip to content
Advertisement

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

Advertisement

Answer

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')]);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement