Laravel eloquent model - model extends model

混江龙づ霸主 提交于 2019-12-12 12:29:41

问题


is it possible to extend a laravel 4 eloquent model with another model, let's say i have a user model extending the eloquent class and additionally there is a second class, a administrator class extending the user class?

If i just linked the administrator class to the user i'd have to access the administrators attributes by first getting the administrator attribute of the user and then getting the admins attributes.

EDIT:

Let's say I have the Administrator not extending the User. I'd have to access e.g. the phone number(a administrators attribute) like this $user = User::find(1); $phone = $user->administrator->phone; but by letting the Administrator extend the User I am able to access the phone number directly like this maybe $user = Administrator::find(1); (Note that the id passed to find the Administrator is the same like the one I use to get the user. Normally I would have to pass the real id of the entry in the Administrator database) $phone = $user->phone; At the same time it would be possible to access an attribute of the user class e.g. $phone = $user->email;

or maybe there is a better solution to achieve this or it makes no sense to use it like this, if so, feel free to tell me


回答1:


This is a good idea in principle, a bad idea in practice. If both of your models use the same table and the only difference is a field, there is no point in adding model pollution. Worse still, you'd have to modify the way Laravel handles relationships (one-to-many) to intelligently return either an Administrator or User object when getting users through other models.

Consider doing the following instead:

 class User extends \Laravel\Eloquent {
     public function isAdministrator() { return !!$this->is_admin; }
     public static function findAdministrator($r=false) {
        if ($r) return self::where("is_admin","=",true)->where("id","=",(int)$r);
        else return self::where("is_admin","=",true);
     }
 }

Doing this opens the two new methods on the model: isAdministrator, which returns boolean true if the user is an admin, boolean false otherwise. findAdministrator, which behaves like find but selectively picks admins.

This allows you to not have two models for what is essentially a relationship (an admin remains an user, after all). It also allows you to easily pick out what you need through useful, atomic methods.



来源:https://stackoverflow.com/questions/16565486/laravel-eloquent-model-model-extends-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!