Laravel eloquent 使用关系列更新列
Laravel eloquent update column using relationship column
如何实现这个查询?
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => DB::raw('catalog.price')]);
这不起作用,它显示未定义 table...我尝试输入 table 的名称,但它是一样的。
在互联网上,我总能找到简单的查询:
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => 5]);
好的!当我想用相同的值更新所有行时很容易,另外当你想用相同 table 的列更新时也很容易,例如:
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => DB::raw('price_alternative')]);
但是如何将另一个 table 的列与关系一起使用呢?我还没有找到解决方案。
我知道这可以使用整个原始查询来解决,但我想知道是否可以通过 eloquent 方式
您可能需要在查询生成器上加入 catalog
table。这与使用 with()
不同。类似于
Sale::whereIn('id', $ids)
->join('catalog', 'sales.catalog_id', '=', 'catalog.id')
->update(['price' => DB::raw('catalog.price')]);
这并不比@Qirel 的回答好,但它是Eloquent 方式,我喜欢这样,因为这样更清楚。
$Sales = Sale::whereIn('sales.id', $ids)
->with('Cat')->get();
$Sales->map(function($q){
$q->price = $q->Cat->price;
$q->save();
});
假设您在销售模型中有此关系代码:
public function Cat()
{
return $this->hasOne(CatModel::class, 'id', 'catalog_id');
}
如何实现这个查询?
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => DB::raw('catalog.price')]);
这不起作用,它显示未定义 table...我尝试输入 table 的名称,但它是一样的。
在互联网上,我总能找到简单的查询:
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => 5]);
好的!当我想用相同的值更新所有行时很容易,另外当你想用相同 table 的列更新时也很容易,例如:
Sale::with(['catalog'])
->whereIn('id', $ids)
->update(['price' => DB::raw('price_alternative')]);
但是如何将另一个 table 的列与关系一起使用呢?我还没有找到解决方案。
我知道这可以使用整个原始查询来解决,但我想知道是否可以通过 eloquent 方式
您可能需要在查询生成器上加入 catalog
table。这与使用 with()
不同。类似于
Sale::whereIn('id', $ids)
->join('catalog', 'sales.catalog_id', '=', 'catalog.id')
->update(['price' => DB::raw('catalog.price')]);
这并不比@Qirel 的回答好,但它是Eloquent 方式,我喜欢这样,因为这样更清楚。
$Sales = Sale::whereIn('sales.id', $ids)
->with('Cat')->get();
$Sales->map(function($q){
$q->price = $q->Cat->price;
$q->save();
});
假设您在销售模型中有此关系代码:
public function Cat()
{
return $this->hasOne(CatModel::class, 'id', 'catalog_id');
}