根据laravel中现有列中的值添加新列

时间:2019-03-29 08:18:01

标签: php mysql laravel

我在表格中有这些列:

  • id
  • 名称
  • 状态
  • 类型

状态应为01

  • 0表示无效
  • 1表示无效。

我想在商品列表中添加status_name字段。这可能吗?

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

$items->get();

我不想使用循环。有什么办法只能在不使用循环的情况下对此查询执行此操作。

3 个答案:

答案 0 :(得分:0)

您需要遍历item集合并应用条件:

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

答案 1 :(得分:0)

使用迁移在表中添加字段

$table->string('status_name');

在控制器中

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

答案 2 :(得分:0)

如果不允许循环访问数据,则可以使用generated columnsMySQL enumerations

创建迁移以将列添加到表中

php artisan make:migration add_status_name_to_items_table --table=items

使用存储的生成的列,如下所示:

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

虚拟生成的列为:

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

请注意,枚举值的顺序很重要,并且可以使用枚举值的索引而不是SQL语句中的那些字符串值

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

您无需在更新或插入内容中包含status_name,它会自动设置

希望能有所帮助

相关问题