Table of Contents
1、简介
2、访问器 & 修改器
3、日期修改器
4、属性转换
Home Backend Development PHP Tutorial [ Laravel 5.2 文档 ] Eloquent ORM -- 访问器&修改器

[ Laravel 5.2 文档 ] Eloquent ORM -- 访问器&修改器

Jun 23, 2016 pm 01:18 PM

1、简介

访问器和修改器允许你在获取模型属性或设置其值时格式化Eloquent 属性。例如,你可能想要使用Laravel加密器对存储在数据库中的数据进行加密,并且在 Eloquent 模型中访问时自动进行解密。

除了自定义访问器和修改器,Eloquent 还可以自动转换日期字段为Carbon实例甚至将文本转换为JSON。

2、访问器 & 修改器

定义访问器

要定义一个访问器,需要在模型中创建一个 getFooAttribute方法,其中 Foo是你想要访问的字段名(使用驼峰式命名规则)。在本例中,我们将会为 first_name属性定义一个访问器,该访问器在获取 first_name的值时被 Eloquent 自动调用:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{    /**     * 获取用户的名字     *     * @param  string  $value     * @return string     */    public function getFirstNameAttribute($value)    {        return ucfirst($value);    }}
Copy after login

正如你所看到的,该字段的原生值被传递给访问器,然后返回处理过的值。要访问该值只需要简单访问 first_name即可:

$user = App\User::find(1);$firstName = $user->first_name;
Copy after login

定义修改器

要定义一个修改器,需要在模型中定义 setFooAttribute方法,其中 Foo是你想要访问的字段(使用驼峰式命名规则)。接下来让我们为 first_name属性定义一个修改器,当我们为模型上的 first_name赋值时该修改器会被自动调用:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{    /**     * 设置用户的名字     *     * @param  string  $value     * @return string     */    public function setFirstNameAttribute($value)    {        $this->attributes['first_name'] = strtolower($value);    }}
Copy after login

该修改器获取要被设置的属性值,允许你操纵该值并设置 Eloquent 模型内部属性值为操作后的值。例如,如果你尝试设置 Sally的 first_name属性:

$user = App\User::find(1);$user->first_name = 'Sally';
Copy after login

在本例中, setFirstNameAttribute方法会被调用,传入参数为 Sally,修改器会对其调用 strtolower函数并将处理后的值设置为内部属性的值。

3、日期修改器

默认情况下,Eloquent 将会转化 created_at和 updated_at列的值为 Carbon 实例,该类继承自 PHP 原生的 Datetime类,并提供了各种有用的方法。

你可以自定义哪些字段被自动调整修改,甚至可以通过重写模型中的 $dates属性完全禁止调整:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{    /**     * 应该被调整为日期的属性     *     * @var array     */    protected $dates = ['created_at', 'updated_at', 'disabled_at'];}
Copy after login

如果字段是日期格式时,你可以将其值设置为 UNIX 时间戳,日期字符串( Y-m-d),日期-时间字符串, Datetime/Carbon实例,日期的值将会自动以正确格式存储到数据库中:

$user = App\User::find(1);$user->disabled_at = Carbon::now();$user->save();
Copy after login

正如上面提到的,当获取被罗列在 $dates数组中的属性时,它们会被自动转化为 Carbon实例,允许你在属性上使用任何 Carbon的方法:

$user = App\User::find(1);return $user->disabled_at->getTimestamp();
Copy after login

默认情况下,时间戳的格式是“Y-m-d H:i:s”,如果你需要自定义时间戳格式,在模型中设置 $dateFormat属性,该属性决定日期属性存储在数据库以及序列化为数组或 JSON 时的格式:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class Flight extends Model{    /**     * 模型日期的存储格式     *     * @var string     */    protected $dateFormat = 'U';}
Copy after login

4、属性转换

模型中的 $casts属性为属性字段转换到通用数据类型提供了便利方法 。 $casts属性是数组格式,其键是要被转换的属性名称,其值时你想要转换的类型。目前支持的转换类型包括: integer, real, float, double, string, boolean, object, array, collection, date和 datetime。

例如,让我们转换 is_admin属性,将其由 integer类型(0或1)转换为 boolean类型:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{    /**     * 应该被转化为原生类型的属性     *     * @var array     */    protected $casts = [        'is_admin' => 'boolean',    ];}
Copy after login

现在, is_admin属性在被访问时总是被转换为 boolean,即使底层存储在数据库中的值是 integer:

$user = App\User::find(1);if ($user->is_admin) {    //}
Copy after login

数组转换

array类型转换在处理被存储为序列化 JSON 格式的字段时特别有用,例如,如果数据库有一个 TEXT 字段类型包含了序列化JSON,添加 array类型转换到该属性将会在 Eloquent 模型中访问其值时自动将其反序列化为 PHP 数组:

<?phpnamespace App;use Illuminate\Database\Eloquent\Model;class User extends Model{    /**     * 应该被转化为原生类型的属性     *     * @var array     */    protected $casts = [        'options' => 'array',    ];}
Copy after login

类型转换被定义后,访问 options属性将会自动从 JSON 反序列化为 PHP 数组,反之,当你设置 options属性的值时,给定数组将会自动转化为 JSON 以供存储:

$user = App\User::find(1);$options = $user->options;$options['key'] = 'value';$user->options = $options;$user->save();
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles