首先以App\User模型为例
1、$table属性
表名,对应数据库中的表名
2、 fillable( guarded)属性
fillable和 guarded属性都是laravel的批量赋值方法create()的, fillable表示在create()方法中可以被赋值的字段,对应的是 guarded表示在create()方法中不能被赋值的字段
3、$hidden属性
$hidden属性可以隐藏字段,使其不出现在数组或者json格式中。
$user = Auth::user();
dump($user);exit;
输出结果为:
#attributes: array:13 [▼
"id" => 1
"name" => "admin"
"email" => ""
"description" => "超级管理员"
"password" => "$2y$10$ib2n.ZbZFvZdt7S8N.9tKuON8QzedokbHOyxMX/7m9Iz66YBCHqyy"
"remember_token" => "fTldAutDKCRGRpKvwVtYyDsdi79A1loGlwJBBgHGJSK6ih26pFdo5qvfN8VG"
"status" => "NORMAL"
"assigned_rate" => 0
"supplier_id" => 0
"agency_id" => 12
"deleted_at" => null
"created_at" => "2015-11-02 05:13:17"
"updated_at" => "2017-03-24 09:35:05"
转换数组:
$user = Auth::user()->toArray();
dump($user);exit;
结果为:
array:11 [▼
"id" => 1
"name" => "admin"
"email" => ""
"description" => "超级管理员"
"status" => "NORMAL"
"assigned_rate" => 0
"supplier_id" => 0
"agency_id" => 12
"deleted_at" => null
"created_at" => "2015-11-02 05:13:17"
"updated_at" => "2017-03-24 09:35:05"
]
转换成JSON格式:
$user = Auth::user()->toJson();
dump($user);exit;
输出结果为:
"{"id":1,"name":"admin","email":"[email protected]","description":"\u8d85\u7ea7\u7ba1\u7406\u5458","status":"NORMAL","assigned_rate":0,"supplier_id":0,"agency_id":12,"deleted_at":null,"created_at":"2015-11-02 05:13:17","updated_at":"2017-03-24 09:35:05"}"
可见hidden属性的作用
4、$dates属性
$dates属性里面包含的字段可以直接后面跟carbon类时间操作的任何方法,例如一个模型:
class User extends Model{
/**
* 应该被调整为日期的属性
*
* @var array
*/
protected $dates = ['created_at', 'updated_at', 'disabled_at'];
}
$user = App\User::find(1);
return $user->disabled_at->getTimestamp();
5、$attributes属性
默认给数据库里的一个字段赋值
protected $attributes = [
'user_limit' => 100,
];
默认给这个模型表的user_limit字段赋上100的值
6、$timestamps属性
laravel默认会在create()创建数据的时候,将created_at字段更新,如果是进行修改操作,将会更新updated_at属性里面的值
如果将
public $timestamps = false;
则create方法执行时,不会修改对应的值