当前位置 : 主页 > 手机开发 > 其它 >

继承 – 在Laravel 4中,Eloquent模型的继承属性为null

来源:互联网 收集:自由互联 发布时间:2021-06-19
基本上我的问题是我的模型不会从超类中继承所需的属性.我已经发现了这个问题: inherited attributes are null,它解决了同样的问题.但是解决方案对我不起作用. 我尝试过,但是可填充属性没
基本上我的问题是我的模型不会从超类中继承所需的属性.我已经发现了这个问题: inherited attributes are null,它解决了同样的问题.但是解决方案对我不起作用.

我尝试过,但是可填充属性没有设置.我的子类无法访问属性.

也许我做错了什么?

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

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

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

我设计了我的模型,以便Advisor和Customer继承超级用户:

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);
    }
    ...
 }

我还尝试在设置fillables之前调用构造函数,如: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;
}

但这显然是丑陋的,效率不高而且不好.
我真的没办法继承这些属性吗?我错过了什么?

提前致谢

由于您在数据库中设计了单个表继承结构,因此您可以使用Laravel eloquent relationship函数解释您的问题的另一种方法: 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;
网友评论