laravel 使用其他列值进行 Eloquent 更新

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31118045/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:51:29  来源:igfitidea点击:

Use other column values for Eloquent update

phplaraveleloquentlaravel-5

提问by lesssugar

I would like to perform an UPDATEusing Eloquent, that will set column_cvalue using values of column_aand column_bof the same table. Basically, something like this:

我想执行一个UPDATEusing Eloquent,它将column_c使用同一个表的值column_a和值来设置值column_b。基本上,是这样的:

User::where('id', '>', 0)
        ->update(['column_c' => $this->column_a + $this->column_b]);

where $this->column_aand $this->column_bwould bethe actual values from the current row.

其中$this->column_a$this->column_b将是当前行的实际值。

MySQL equivalent:

MySQL等价物:

UPDATE `user` WHERE id > 0 SET column_c = column_a + column_b;

Note: The code above is just an example to show the idea. It's notthe actual implementation (which would be creating a DB redundancy).

注意:上面的代码只是展示这个想法的一个例子。这不是实际的实现(这将创建数据库冗余)。

How do I perform such update in Laravel 5.1? I would really like to avoid a foreach.

如何在 Laravel 5.1 中执行此类更新?我真的很想避免foreach.

回答by P??

Maybe DB::rawcan help. This will allow you to use any standard sql query to combine your data:

也许DB::raw可以提供帮助。这将允许您使用任何标准的 sql 查询来组合您的数据:

User::where('id', '>', 1)
    ->update(['column_c' => DB::raw( CONCAT(column_a, '-', column_b) )]);

回答by ThatMSG

You could use an override.. Somthing like this:

你可以使用覆盖..像这样的事情:

use Illuminate\Database\Eloquent\Model;

class MyModel extends Model {

    public function save(array $options = []){
        $this->column_a = $this->column_b;
        parent::save($options);
    }
}

Edit: This might help you as well: laravel model callbacks after save, before save, etc

编辑:这也可能对您有所帮助: 保存后、保存前等的 Laravel 模型回调