【问题标题】:Inherited attributes from Eloquent models are null in Laravel 4从 Eloquent 模型继承的属性在 Laravel 4 中为空
【发布时间】:2014-05-07 14:58:30
【问题描述】:

基本上我的问题是我的模型没有从它们的超类继承所需的属性。我已经找到了这个问题:inherited attributes are null,它解决了同样的问题。但是,该解决方案对我不起作用。

我试过了,但是没有设置可填充属性。我的子类无权访问这些属性。

也许我做错了什么?


额外信息(我猜不是必需的)

我的情况是这样的:用户(表“用户”)可以是顾问(表“顾问”)和/或客户(表“客户”)。

所以关于用户的所有一般信息; first_name, last_name, ... 存储在 users 表中。 customer_number 或功能等特定信息存储在相应的表中。顾问和客户都有不同的关系,因为他们在应用程序中扮演不同的角色。


我设计了我的模型,以便顾问和客户从超类 User 继承:

class User extends Eloquent implements UserInterface, RemindableInterface {

    protected $fillable = array('email', 'first_name', 'last_name', 'email', 'gender', 'phone_number', 'profile_picture');
    protected $hidden = array('password');
    protected $guarded = array('id', 'password');

    protected $table = 'users';

    ...

}

还有我的顾问班:

class Advisor extends User {

    protected $table = 'advisors';
    protected $fillable = array('active', 'function', 'description') ;

    //this does not work!
    public function __construct (array $attributes = array()) {
        // the static function getFillableArray() just returns the fillables array      
        $this->fillable = array_merge ($this->fillable, parent::getFillableArray());
        parent::__construct($attributes);
    }
    ...
 }

我还尝试在设置可填充项之前调用构造函数,如this question 所建议的那样。也没用。

起作用的是,像这样在 User 超类中编写访问器:

// Attribute getters - Inheritence not working
public function getFirstNameAttribute($value)
{
    $returnValue = null;
    if($value){
        $returnValue = $value;
    }else{
        $returnValue = User::find($this->id)->first_name;
    }
    return $returnValue;
}

但由于显而易见的原因,这很丑陋,效率低下且不好。 我真的没有办法继承这些属性吗?我错过了什么?

提前致谢

【问题讨论】:

    标签: inheritance attributes null laravel-4 superclass


    【解决方案1】:

    由于您在数据库中设计了单表继承结构,因此您可以使用另一种方法来解决您的问题,您可以使用此处解释的 Laravel 雄辩关系函数:http://laravel.com/docs/eloquent#relationships。这将允许您访问超类的属性,例如:

    //in your Advisor model
    public function profile()
    {
        return $this->belongsTo('User');
    }
    
    //to call for advisor's first name
    Advisor::find($id)->profile->first_name;
    

    【讨论】:

    • 天哪,我完全忽略了这一点。尽管我实际上想跟踪类本身的属性。但我认为这是一个可以接受的答案。我将在本周晚些时候发布我的解决方案。我使用 $appends 属性,这样我就可以用它们填充 User 类,但基本上这是您建议的解决方案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2018-06-16
    • 2014-06-17
    • 2015-01-26
    • 2021-11-19
    • 2014-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多