Inheritance in Laravel framework

回眸只為那壹抹淺笑 提交于 2020-01-14 06:47:05

问题


Is possibile to use inheritance in laravel model? I explain:

is possible to exend a model, which extends eloquent class?

class A extends Eloquent
{
}

class B extends A
{
}

A e B are also 2 different tables and B has A_id as foreignkey and other fields. How could be the constructor of class B? is it a ragionable solution or better use hasOne relationship?

no every A object are also B object. Es. user and teacher

Thank you


回答1:


I’m having difficulty understanding your supplementary details, but in answer to the actual question: yes, it is possible to extend Eloquent models.

<?php
class User extends \Eloquent {

    protected $table = 'users';

}

class Student extends User {

    protected $table = 'students';

}

Be warned though, that any methods (such as relations, scopes etc) will propagate to the extending class. If this is not desired, then create a base class that has the minimum of what you need, and then sub-class it with your specific types, i.e. Student, Administrator etc.

Another approach is to use interfaces. So if you know models need the same attributes but will say, have different relations; then you can create an interface to add those constraints:

<?php
interface UserInterface {

    public function getName();

}

class User extends \Eloquent implements UserInterface {

    protected $table = 'users';

    public function getName()
    {
        return $this->name;
    }

}

class Student extends \Eloquent implements UserInterface {

    protected $table = 'students';

    public function getName()
    {
        return $this->name;
    }

    public function courses()
    {
        return $this->belongsToMany('Course');
    }

    public function grades()
    {
        return $this->hasMany('Grade');
    }

}



回答2:


I resolve with

class A extends Eloquent 
{
   protected $table  = 'a';
}

class B extends A
{
   protected $table  = 'b';
   protected $primaryKey = 'a_id';
}

but in the main function:

$f = B::find(1);
$f->method();

where the method() is a method of A class, the system gives to me an mysql error:

select * fromCwhereC.B_id= 1

the error is B_id. It should be A_id cause the method shold be applied from subobject of the class, not from the class



来源:https://stackoverflow.com/questions/25036593/inheritance-in-laravel-framework

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