📜  跳过模型访问器 (1)

📅  最后修改于: 2023-12-03 15:28:14.835000             🧑  作者: Mango

跳过模型访问器

在使用 Laravel 开发时,我们经常会用到 Eloquent ORM。使用 Eloquent ORM 可以方便地进行数据库操作,而模型访问器是 Eloquent ORM 中的一个重要特性。它允许我们定义在访问模型属性时自动处理的逻辑。但有时候我们想要跳过模型访问器,直接获取属性值。本篇文章将讲述如何跳过模型访问器来获取属性值。

使用 getOriginal() 方法

要跳过模型访问器并获取原始属性值,可以使用 getOriginal() 方法。它返回原始模型属性值的数组,其中包括跳过了修改器和访问器处理的值。以下是一个简单的例子:

$user = new User();
$user->name = 'John Doe';
$user->save();

// 使用模型访问器获得name
echo $user->name; // 输出 "John Doe"

// 跳过模型访问器获得原始属性
echo $user->getOriginal('name'); // 输出 "John Doe"
使用 getAttributes() 方法

如果要获取模型的所有属性值(包括跳过所有访问器),可以使用getAttributes() 方法。此方法返回一个包含所有属性的数组。以下是一个例子:

$user = new User();
$user->name = 'John Doe';
$user->email = 'johndoe@example.com';
$user->save();

// 使用模型访问器获得name
echo $user->name; // 输出 "John Doe"

// 获取所有模型属性值
$attributes = $user->getAttributes();

echo $attributes['name'];  // 输出 "John Doe"
echo $attributes['email']; // 输出 "johndoe@example.com"
使用 toArray() 方法

如果要获取模型的所有属性值,并将它们转换为一个数组,可以使用toArray() 方法。此方法将返回一个包含所有属性的数组,其中包括跳过访问器处理的原始值。以下是一个例子:

$user = new User();
$user->name = 'John Doe';
$user->email = 'johndoe@example.com';
$user->save();

// 使用模型访问器获得name
echo $user->name; // 输出 "John Doe"

// 将模型转换为一个数组
$attributes = $user->toArray();

echo $attributes['name'];  // 输出 "John Doe"
echo $attributes['email']; // 输出 "johndoe@example.com"

通过使用getOriginal() 方法、getAttributes()方法或toArray()方法,我们可以轻松地跳过模型访问器并获取模型属性的原始值。