Laravel5.1学习笔记22 Eloquent 调整修改
Eloquent: Mutators
Introduction
Accessors and mutators allow you to format Eloquent attributes when retrieving them from a model or setting their value. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.
In addition to custom accessors and mutators, Eloquent can also automatically cast date fields to Carbon instances or even cast text fields to JSON.
Accessors & Mutators
Defining An Accessor
To define an accessor, create a getFooAttribute
method on your model where Foo
is the "camel" cased name of the column you wish to access. In this example, we'll defined an accessor for the first_name
attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of first_name
:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Get the user's first name.
*
* @param string $value
* @return string
*/
public function getFirstNameAttribute($value)
{
return ucfirst($value);
}
}
As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the mutator, you may simply access the first_name
attribute:
$user = App\User::find(1);
$firstName = $user->first_name;
Defining A Mutator
To define a mutator, define a setFooAttribute
method on your model where Foo
is the "camel" cased name of the column you wish to access. So, again, let's define a mutator for the first_name
attribute. This mutator will be automatically called when we attempt to set the value of the first_name
attribute on the model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* Set the user's first name.
*
* @param string $value
* @return string
*/
public function setFirstNameAttribute($value)
{
$this->attributes['first_name'] = strtolower($value);
}
}
The mutator will receive the value that is being set on the attribute, allowing you to manipulate the value and set the manipulated value on the Eloquent model's internal$attributes
property. So, for example, if we attempt to set the first_name
attribute to Sally
:
$user = App\User::find(1);
$user->first_name = 'Sally';
In this example, the setFirstNameAttribute
function will be called with the value Sally
. The mutator will then apply the strtolower
function to the name and set its value in the internal $attributes
array.
Date Mutators
By default, Eloquent will convert the created_at
and updated_at
columns to instances ofCarbon, which provides an assortment of helpful methods, and extends the native PHPDateTime
class.
You may customize which fields are automatically mutated, and even completely disable this mutation, by overriding the $dates
property of your model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be mutated to dates.
*
* @var array
*/
protected $dates = ['created_at', 'updated_at', 'disabled_at'];
}
When a column is considered a date, you may set its value to a UNIX timestamp, date string (Y-m-d
), date-time string, and of course a DateTime
/ Carbon
instance, and the date's value will automatically be correctly stored in your database:
$user = App\User::find(1);
$user->disabled_at = Carbon::now();
$user->save();
As noted above, when retrieving attributes that are listed in your $dates
property, they will automatically be cast to Carbon instances, allowing you to use any of Carbon's methods on your attributes:
$user = App\User::find(1);
return $user->disabled_at->getTimestamp();
Attribute Casting
The $casts
property on your model provides a convenient method of converting attributes to common data types. The $casts
property should be an array where the key is the name of the attribute being cast, while the value is the type you wish to cast to the column to. The supported cast types are: integer
, real
, float
, double
, string
, boolean
,object
and array
.
For example, let's cast the is_admin
attribute, which is stored in our database as an integer (0
or 1
) to a boolean value:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'is_admin' => 'boolean',
];
}
Now the is_admin
attribute will always be cast to a boolean when you access it, even if the underlying value is stored in the database as an integer:
$user = App\User::find(1);
if ($user->is_admin) {
//
}
Array Casting
The array
cast type is particularly useful when working with columns that are stored as serialized JSON. For example, if your database has a TEXT
field type that contains serialized JSON, adding the array
cast to that attribute will automatically deserialize the attribute to a PHP array when you access it on your Eloquent model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be casted to native types.
*
* @var array
*/
protected $casts = [
'options' => 'array',
];
}
Once the cast is defined, you may access the options
attribute and it will automatically be deserialized from JSON into a PHP array. When you set the value of the options
attribute, the given array will automatically be serialized back into JSON for storage:
$user = App\User::find(1);
$options = $user->options;
$options['key'] = 'value';
$user->options = $options;
$user->save();
Laravel5.1学习笔记22 Eloquent 调整修改的更多相关文章
- Laravel5.1学习笔记23 Eloquent 序列化
Eloquent: Serialization Introduction Basic Usage Hiding Attributes From JSON Appending Values To JSO ...
- 【转】Pandas学习笔记(三)修改&添加值
Pandas学习笔记系列: Pandas学习笔记(一)基本介绍 Pandas学习笔记(二)选择数据 Pandas学习笔记(三)修改&添加值 Pandas学习笔记(四)处理丢失值 Pandas学 ...
- Ext.Net学习笔记22:Ext.Net Tree 用法详解
Ext.Net学习笔记22:Ext.Net Tree 用法详解 上面的图片是一个简单的树,使用Ext.Net来创建这样的树结构非常简单,代码如下: <ext:TreePanel runat=&q ...
- SQL反模式学习笔记22 伪键洁癖,整理数据
目标:整理数据,使不连续的主键Id数据记录变的连续. 反模式:填充断档的数据空缺. 1.不按照顺序分配编号 在插入新行时,通过遍历表,找到的第一个未分配的主键编号分配给新行,来代替原来自动分配的伪主键 ...
- Hadoop学习笔记—22.Hadoop2.x环境搭建与配置
自从2015年花了2个多月时间把Hadoop1.x的学习教程学习了一遍,对Hadoop这个神奇的小象有了一个初步的了解,还对每次学习的内容进行了总结,也形成了我的一个博文系列<Hadoop学习笔 ...
- Dynamic CRM 2015学习笔记(4)修改开发人员资源(发现服务、组织服务和组织数据服务)url地址及组织名
在azure vm上安装了CRM 2015后 Dynamic CRM 2015学习笔记(1)Azure 上安装 CRM 2015, 发现了一个问题,那就是在设置 ->自定义项 –> 开发人 ...
- [原创]java WEB学习笔记22:MVC案例完整实践(part 3)---多个请求对应一个Servlet解析
本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...
- Cocos2d-x 学习笔记(22) TableView
[Cocos2d-x 学习笔记 ]目录 1. 简介 TableView直接继承了ScrollView和ScrollViewDelegate.说明TableView能实现ScrollView拖动cont ...
- Laravel5.1学习笔记18 数据库4 数据填充
简介 编写数据填充类 使用模型工厂类 调用额外填充类 执行填充 #简介 Laravel includes a simple method of seeding your database with t ...
随机推荐
- java基础标识符,关键字,常量
1关键字1.1关键字的概述Java的关键字对java的编译器有特殊的意义,他们用来表示一种数据类型,或者表示程序的结构等,关键字不能用作变量名.方法名.类名.包名.2标识符2.1什么是标识符就是程序员 ...
- 携程Apollo(阿波罗)配置中心在Spring Boot项目快速集成
前提:先搭建好本地的单机运行项目:http://www.cnblogs.com/EasonJim/p/7643630.html 说明:下面的示例是基于Spring Boot搭建的,对于Spring项目 ...
- Servlet基础教程:tutorialspoint-servlet
来自turorialspoint的Servlet基础教程(英文),官网:https://www.tutorialspoint.com/servlets/index.htm 这个教程在国内已经被翻译成中 ...
- java读取大文本文件
原文:http://blog.csdn.net/k21325/article/details/53886160 小文件当然可以直接读取所有,然后放到内存中,但是当文件很大的时候,这个方法就行不通了,内 ...
- Swift可选类型(Optional)之星耀
首先我们先看下Objective-C与Swift语言对于可选nil的不同理解: Objective-C中的nil:表示缺少一个合法的对象,是指向不存在对象的指针,对结构体.枚举等类型不起作用(会返回N ...
- python 区块链程序
python 区块链程序 学习了:https://mp.weixin.qq.com/s?__biz=MzAxODcyNjEzNQ==&mid=2247484921&idx=1& ...
- HDU 1030 数学题
给出两点,求这两点在图上的最短路径 分别以最上,左下,右下为顶点,看这个三角图形 ans=这三种情况下两点的层数差 #include "stdio.h" #include &quo ...
- 进程间通信之-共享内存Shared Memory--linux内核剖析(十一)
共享内存 共享内存是进程间通信中最简单的方式之中的一个. 共享内存是系统出于多个进程之间通讯的考虑,而预留的的一块内存区. 共享内存同意两个或很多其他进程訪问同一块内存,就如同 malloc() 函数 ...
- 使用MyBatis Generator自动生成MyBatis的代码
这两天需要用到MyBatis的代码自动生成的功能,由于MyBatis属于一种半自动的ORM框架,所以主要的工作就是配置Mapping映射文件,但是由于手写映射文件很容易出错,所以可利用MyBatis生 ...
- (转)C3P0配置
C3P0是一个开源的JDBC 连接池,它实现了数据源和JNDI绑定,支持JDBC3规范和JDBC2的标准扩展.目前使用它的开源项目有Hibernate,Spring等. sourceforge 下载: ...