Marc Pont
Marc Pont

Reputation: 1068

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

Upvotes: 3

Views: 2635

Answers (2)

Trần Hữu Hiền
Trần Hữu Hiền

Reputation: 1044

This is not better than answer of @Qirel, but it is Eloquent way, i like this because that's more clearly.

$Sales = Sale::whereIn('sales.id', $ids)
    ->with('Cat')->get();

$Sales->map(function($q){
    $q->price = $q->Cat->price;
    $q->save();
});

Assume you have this relation code in Sale model:

public function Cat()
{
    return $this->hasOne(CatModel::class, 'id', 'catalog_id');
}

Upvotes: 0

Qirel
Qirel

Reputation: 26450

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')]);

Upvotes: 5

Related Questions