【问题标题】:Add new column on the basis of values in the existing column in laravel根据 laravel 现有列中的值添加新列
【发布时间】:2019-08-20 03:20:54
【问题描述】:

我在表格中有这些列:

  • 身份证
  • 姓名
  • 状态
  • 类型

状态应为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();

我不想使用循环。有没有办法只用这个查询而不使用循环来做到这一点。

【问题讨论】:

  • 谢谢,但我不想用循环来做这个我们只能在这个查询中做这个吗?
  • 是的,但是您需要使用 IF 语句编写原始 SQL 查询

标签: php mysql laravel


【解决方案1】:

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

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

php artisan make:migration add_status_name_to_items_table --table=items

使用 stored 生成的列如下:

$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,它会自动设置

希望对你有所帮助

【讨论】:

    【解决方案2】:

    您需要遍历项目集合并应用您的条件,例如:

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

    【讨论】:

    • 谢谢,但我想在没有循环的情况下进行,查询中的条件。这可能吗?
    【解决方案3】:

    使用迁移在表中添加字段

    $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';
            }
       }
    

    【讨论】:

    • $item['status_name'] = $item->status ? 'active' : 'inactive';
    猜你喜欢
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-13
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多