【问题标题】:How do I set an instance variable on an Eloquent model?如何在 Eloquent 模型上设置实例变量?
【发布时间】:2013-09-13 15:05:47
【问题描述】:

如何在 Laravel4 中的 Eloquent 模型上创建动态实例变量?

例如,我想访问 $user->full_name,这将通过连接 $user->first_name 和 $user->last_name 来创建,两者都存储在 DB 中。这是不正确的,但在某种程度上是:

class User extends Eloquent {

  public $full_name = $this->first_name . " " . $this->last_name;

}

【问题讨论】:

    标签: php model laravel eloquent


    【解决方案1】:

    你必须定义一个getFullNameAttributeaccessor method

    class User extends Eloquent {
    
        public function getFullNameAttribute ()
        {
            return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
        }
    }
    

    【讨论】:

    • 我想我宁愿调用类属性而不是方法。有没有办法在数据库数据加载到模型后自动调用方法?
    • 根据文档,您应该可以执行以下操作 paste.laravel.com/QS4 来获取 full_name 属性
    • @Bryant,访问器背后的想法是您可以调用它们,就好像它们只是模型的属性一样。在上面的示例中,您只需执行 $model->full_name。请参阅here 了解更多信息
    猜你喜欢
    • 2018-11-04
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-24
    相关资源
    最近更新 更多