JSON显示代表比特/布尔字段的字符串类型
问题描述:
{
"Status": true,
"Message": "Roles retrieved successfully",
"Data": [
{
"RoleID": 1,
"Role": "Super Admin",
"IsPredefined": "1",
"IsActive" : "1",
}
]
}
我以json格式获取上述结果。我正在使用下面的查询来从MySql数据库中获取数据。JSON显示代表比特/布尔字段的字符串类型
我使用的型号和我的代码是:RoleModel::all()
我使用PHP-Laravel 5.3
有没有什么办法让中的结果如下图所示。
{
"Status": true,
"Message": "Roles retrieved successfully",
"Data": [
{
"RoleID": 1,
"Role": "Super Admin",
"IsPredefined": true,
"IsActive" : true,
}
]
}
问题出现在IsPredefined中。我想要检索它的布尔类型。在数据库中它的类型是位
答
Attribute Casting
我的模式是类似下面
class RoleModel extends Model {
public $table = 'tblrole';
public $primaryKey = 'RoleID';
public $timestamps = true;
}
应该像下面。
class RoleModel extends Model {
public $table = 'tblrole';
public $primaryKey = 'RoleID';
public $timestamps = true;
protected $casts = [
'IsPredefined' => 'boolean'
];
}
此外,数据库中的表必须具有数据类型=“BIT”为布尔值 ,使得它可以仅占据0或1的值。
答
的也许你可以使用if()功能,所以
Select RoleID, Role, if(IsPredefined=1,'true','false') as IsPredefined form tblrole;
如果您使用的雄辩模型,你可以使用Accessors and Mutators所以在你的雄辩模型添加访问方法。
public function getIspredefinedAttribute($value)
{
return ($value==1)?true:false;
}
我正在使用模型,我的代码是:'RoleModel :: all()'所以,使用此解决方案是不可行的。 – Pankaj
您可以使用Accessors。看到更新的答案。 – follio