简体   繁体   中英

Add new column on the basis of values in the existing column in laravel

I have these columns in the table:

  • id
  • name
  • status
  • type

Status should be 0 or 1 .

  • 0 for inactive
  • 1 for inactive.

I want to add status_name field in my item listing. Is this possible?

$items = Item::where('type', 'test');
if(item.active == 1)
{
   // add new column status_name="active"
}
else
{
   // add new column status_name="inactive"
}

$items->get();

I don't want to use loop. Is there any way to do this with this query only without using loop.

You need to loop through the items collection and apply your condition like :

$items = Item::where('type', 'test')->get();
foreach($items as $item){
    $item->status_name = $port->active===1?'active':'inactive';
}

Add field in table using migration

$table->string('status_name');

In controller

$items = Item::where('type', 'test')->get();
    foreach($items as $item){
        if($item->status== 1)
        {
          $item['status_name'] = 'active';
        } else {
          $item['status_name'] = 'inactive';
        }
   }

If looping through data isn't allowed you can use the generated columns and MySQL enumerations .

Create a migration to add the column to the table

php artisan make:migration add_status_name_to_items_table --table=items

Use stored generated column as below:

$table->enum('status_name', ['inactive', 'active'])->after('status')->storedAs("`status` + 1");

Or virtual generated column as:

$table->enum('status_name', ['inactive', 'active'])->after('status')->virtualAs("`status` + 1");

Note that the order of enumerated values is important and it is possible to use the index of enumerated values instead of those string values in SQL statements

+--------+-------------+----------------------+
| status | status_name | index of status_name |
+--------+-------------+----------------------+
|    -   |     NULL    |         NULL         |
+--------+-------------+----------------------+
|    -   |      ''     |           0          |
+--------+-------------+----------------------+
|    0   |  'inactive' |           1          |
+--------+-------------+----------------------+
|    1   |   'active'  |           2          |
+--------+-------------+----------------------+

You don't need to include status_name in your updates or inserts, it'll be set automatically

Hope to be helpful

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM