$model->foo 和 $model->getAttributeValue('foo') 有什么区别?

What's the difference between $model->foo and $model->getAttributeValue('foo')?

当我有一个名为 $model 的 Eloquent 模型实例时,我可以通过两种方式检索其属性值(例如用户名):

$name = $user->name;

$name = $user->getAttributeValue('name');

哪种方式是正确的,这两种检索值的方式有什么区别?

调用模型属性时,

  • 首先调用 __get() 方法。
  • 然后调用getAttribute()方法。
  • 最后 getAttributeValue()getRelationValue() 被调用。

因此,使用 属性 或 getAttributeValue() 获取模型属性基本相同。请记住,它无法访问模型关系。

请注意,大多数(或全部?)Laravel 文档使用属性来访问模型属性。