laravel - laravel mutator:访问其他属性
问题描述
我有一个简单的 Laravel 8 安装,并添加了一个应该访问该模型的其他属性的mutator 。
举个例子:想把名字设置为名字+邮箱地址。
我试过了:
public function setNameAttribute($value) {
$this->attributes['name'] = $value .' - '. $this->attributes['email'];
}
并测试:
>>> User::factory()->make()
[!] Aliasing 'User' to 'App\Models\User' for this Tinker session.
<warning>PHP Warning: Undefined array key "email" in .../app/Models/User.php on line 45</warning>
=> App\Models\User {#3399
name: "Mr. Johathan Becker - ",
email: "dsteuber@example.com",
email_verified_at: "2021-05-07 18:10:35",
#password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
#remember_token: "bihwTV6T4E",
}
所以:$this->attributes
不包含“电子邮件”。
我可以访问该模型的其他属性吗?
我可以想象,即使有可能,mutator也不能保证相关的属性已经设置好了。
更新:matiaslauriti 的评论解决了上面的简化示例。谢谢!设置属性的顺序很重要。之后我可以同时使用$this->attributes['name']
或$this->name
。
我更复杂的用例是:我想为用户($user->posts()->create([...])
)创建一个帖子,并且在设置帖子属性时我想访问“用户”。所以在这种情况下,用户已经设置好了,我们可以假设“用户”是可用的。但是在 Post mutator $this->user 中给出了 null。建议?
解决方案
您可以尝试$this->email
代替$this->attributes['email']
推荐阅读
- java - Lucene 通过 ID 缓慢检索文档
- oracle - 删除所有雇佣率高于其经理的员工
- r - R中偶数和奇数的If Else语句
- python - 需要帮助理解 Python 中的循环程序/嵌套循环
- sockets - 如何在 pyOpenSSL 中使用 CRL?
- php - Open PDF in new tab using PHP
- r - ggplot2中雷达图中未表示的线和区域
- java - Gradle 同步失败:所有 Firebase 库必须高于或低于 14.0.0
- c# - C# Windows Form KeyCombination Detect 失败,没有任何反馈
- django - 单输入django表单