zoukankan      html  css  js  c++  java
  • laravel5 怎么获取数组形式的数据

    当构建 JSON API 时,您可能常常需要把模型和关联对象转换成数组或JSON。所以Eloquent里已经包含了这些方法。要把模型和已载入的关联对象转成数组,可以使用 toArray方法:

    $user = User::with('roles')->first();
    return $user->toArray();
    注意:也可以把整个的模型集合转换成数组:
    return User::all()->toArray();
    将模型转换成 JSON

    要把模型转换成 JSON,可以使用 toJson 方法:

    return User::find(1)->toJson();
    从路由中返回模型

    注意当模型或集合被转换成字符串类型时会自动转换成 JSON 格式,这意味着您可以直接从路由返回 Eloquent 对象!

    Route::get('users', function()
    {
    return User::all();
    });
    转换成数组或 JSON 时隐藏属性
    http://wenda.golaravel.com/question/1663

    有时您可能想要限制能出现在数组或 JSON 格式的属性数据,比如密码字段。只要在模型里增加 hidden 属性即可

    class User extends Model {
    protected $hidden = ['password'];
    }
    注意: 要隐藏关联数据,要使用关联的方法名称,而不是动态获取的属性名称。
    此外,可以使用 visible 属性定义白名单:

    protected $visible = ['first_name', 'last_name'];
    有时候您可能想要增加不存在数据库字段的属性数据。这时候只要定义一个获取器即可:

    public function getIsAdminAttribute()
    {
    return $this->attributes['admin'] == 'yes';
    }
    定义好获取器之后,再把对应的属性名称加到模型里的 appends 属性:

    protected $appends = ['is_admin'];
    把属性加到 appends 数组之后,在模型数据转换成数组或 JSON格式时就会有对应的值。在 appends数组中定义的值同样遵循模型中 visible和 hidden的设定

  • 相关阅读:
    Android框架: MVC MVP MVVM
    Apache Tomcat -8.0.45
    【MySQL】Database connections will be migrated
    MySQL(mysql-installer-community-5.7.18.1 Windows10)
    代码版本控制(Source Control)
    HTML 5
    微信小程序
    Android Studio 2.3.3 安装
    React Native
    2018面向对象程序设计(Java)第12周学习指导及要求
  • 原文地址:https://www.cnblogs.com/lxwphp/p/15454160.html
Copyright © 2011-2022 走看看