Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use other column values for Eloquent update

Tags:

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.

like image 892
lesssugar Avatar asked Jun 29 '15 14:06

lesssugar


People also ask

How do you UPDATE a column based on another column in SQL?

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.

How UPDATE a column value with another column in the same table in MySQL?

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 ...

How do you UPDATE a record in Laravel?

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.

Is eloquent an ORM?

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.


1 Answers

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) )]);
like image 188
Pᴇʜ Avatar answered Sep 18 '22 03:09

Pᴇʜ