I would like to perform an UPDATE
using Eloquent, that will set column_c
value using values of column_a
and column_b
of the same table. Basically, something like this:
User::where('id', '>', 0)
->update(['column_c' => $this->column_a + $this->column_b]);
where $this->column_a
and $this->column_b
would be the actual values from the current row.
MySQL equivalent:
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 not the 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
.
UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.
In MySQL, if you want to update a column with the value derived from some other column of the same table we can do so by using a SELF JOIN query and if you wish to modify the value derived from another column like maybe get a substring from the text or break the string using some delimiter, then we can use the ...
We can update the records using the DB facade with update method. The syntax of update method is as shown in the following table. Run an update statement against the database.
Eloquent is an object relational mapper (ORM) that is included by default within the Laravel framework. An ORM is software that facilitates handling database records by representing data as objects, working as a layer of abstraction on top of the database engine used to store an application's data.
Maybe DB::raw
can help. This will allow you to use any standard sql query to combine your data:
User::where('id', '>', 1)
->update(['column_c' => DB::raw( CONCAT(column_a, '-', column_b) )]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With