laravel5.6实现数值转换

2020-09-03 11:56:29

在laravel框架中,如果希望从数据库中取出的值就是我们希望的类型,可以使用laravel框架模型中的$casts属性值来将需要的字段转换成需要的类型,用法如下:

<?phpnamespace App;use IlluminateDatabaseEloquentModel;class User extends Model{  /**   * 应该被转化为原生类型的属性   *   * @var array   */  protected $casts = [    //字段=>希望转换的类型    'is_admin' => 'boolean',  ];}

总结来说,就是给需要转换的表的对应模型中添加$casts属性,目前支持转换的类型有integer, real, float, double, string, boolean, object,array,collection,date,datetime 和 timestamp。

相关文章 大家在看