Php 基于laravel中现有列中的值添加新列
表中有以下列:Php 基于laravel中现有列中的值添加新列,php,mysql,laravel,Php,Mysql,Laravel,表中有以下列: 身份证 名字 地位 类型 状态应为0或1 0表示不活动 1表示不活动 我想在我的物品清单中添加status\u name字段。这可能吗 $items = Item::where('type', 'test'); if(item.active == 1) { // add new column status_name="active" } else { // add new column status_name="inactive" } $items->
- 身份证
- 名字
- 地位
- 类型
0
或1
- 0表示不活动
- 1表示不活动
status\u 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();
我不想使用循环。有没有办法只使用此查询而不使用循环来执行此操作。您需要在items集合中循环并应用您的条件,如:
$items = Item::where('type', 'test')->get();
foreach($items as $item){
$item->status_name = $port->active===1?'active':'inactive';
}
使用迁移在表中添加字段
$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';
}
}
如果不允许在数据中循环,则可以使用and 创建一个迁移以将列添加到表中
php artisan make:migration add_status_name_to_items_table --table=items
使用存储的生成列,如下所示:
$table->enum('status_name', ['inactive', 'active'])->after('status')->storedAs("`status` + 1");
或virtual生成的列为:
$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 |
+--------+-------------+----------------------+
您不需要在更新或插入中包含状态\u名称
,它将自动设置
希望对您有所帮助这可能会有所帮助,谢谢,但我不想使用循环执行此操作。我们可以仅在该查询中执行此操作吗?是的,但您需要使用IF语句编写原始SQL查询谢谢,但我希望在查询中不使用循环条件执行此操作。这可能吗?
$item['status\u name']=$item->status?”活动':'不活动'代码>