码迷,mamicode.com
首页 > 其他好文 > 详细

laravel ORM序列化

时间:2017-05-03 10:30:05      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:protected   href   tle   isa   方法   user   func   xtend   序列化   

在laravel项目 常常需要把eloquent ORM序列化为数组或者json,Eloquent 提供了便捷方法以便实现这些转换,以及控制哪些属性被包含到序列化中。

1.序列化为数组

 $user = App\User::with(‘roles‘)->first();return $user->toArray();

2.序列化为json $user = App\User::find(1);return $user->toJson();

3.在json中隐藏属性 

在模型中定义$hidden属性 例如  protected $hidden = [‘password‘];

同理通过定义$visible 属性 来控制模型中模型数组或者json中的属性白名单。例如 protected $visible = [‘first_name‘, ‘last_name‘];

4.若要在模型中临时的暴露某个属性  return $user->makeVisible(‘attribute‘)->toArray();

5.若要追加数据库不存在的字段到数组或者json返回值时候 需要先定义一个访问器 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * 为用户获取管理员标识
     *
     * @return bool
     */
    public function getIsAdminAttribute()
    {
        return $this->attributes[‘admin‘] == ‘yes‘;
    }
}
定义好访问器后,添加字段名到该模型的 appends 属性
 protected $appends = [‘is_admin‘];



laravel ORM序列化

标签:protected   href   tle   isa   方法   user   func   xtend   序列化   

原文地址:http://www.cnblogs.com/zhangwei0909/p/6800496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!