【问题标题】:Laravel eloquent update column using relationship columnLaravel eloquent 使用关系列更新列
【发布时间】:2020-11-21 00:58:16
【问题描述】:

如何实现这个查询?

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

这不起作用,它显示未定义的表...我试图输入表的名称但它是相同的。

在网上我总能找到简单的查询:

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

好的!当我想用相同的值更新所有行时很容易,此外,当你想用同一个表的列更新时也很容易,例如:

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

但是如何使用具有关系的另一个表的列呢?我还没有找到解决办法。

我知道这可以使用整个原始查询来解决,但我想知道它是否可以通过雄辩的方式来实现

【问题讨论】:

    标签: php laravel eloquent eloquent-relationship


    【解决方案1】:

    这并不比@Qirel的回答好,但它是雄辩的方式,我喜欢这样,因为这样更清楚。

    $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');
    }
    

    【讨论】:

    • 这可能会对性能产生巨大影响,具体取决于 $ids 长度。
    • 是的,我知道,但尝试一种“纯粹”的 Eloquent 方式。您可以使用 Chunk 和 Transaction 来控制性能。这就是为什么我说“这并不比@Qirel 的回答好”
    【解决方案2】:

    您可能需要加入查询构建器上的catalog 表。这与使用with() 不同。类似于

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

    【讨论】:

    • 是的,我想过这个。我总是尝试使用关系而不是连接,但如果没有其他选择,我会选择这个。谢谢。
    • 确实,在适用的情况下使用关系总是更好,但这是您需要加入的情况之一。干杯!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-28
    • 2016-10-15
    • 2014-01-15
    • 2020-03-05
    • 2021-03-30
    • 2014-06-25
    相关资源
    最近更新 更多