【问题标题】:Inheritance in Laravel frameworkLaravel 框架中的继承
【发布时间】:2014-09-22 01:57:12
【问题描述】:

可以在 laravel 模型中使用继承吗?我解释一下:

可以扩展一个模型,扩展 eloquent 类吗?

class A extends Eloquent
{
}

class B extends A
{
}

A e B 也是 2 个不同的表,B 具有 A_id 作为外键和其他字段。 怎么可能是B类的构造函数? 这是一个合理的解决方案还是更好地使用 hasOne 关系?

不是每个 A 对象也是 B 对象。埃斯。用户和老师

谢谢

【问题讨论】:

    标签: php laravel laravel-4 eloquent models


    【解决方案1】:

    我解决了

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

    但在主函数中:

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

    其中method()是A类的方法, 系统给我一个mysql错误:

    select * from `C` where `C`.`B_id` = 1

    错误是B_id。应该是A_id,因为方法应该从类的子对象应用,而不是从类应用

    【讨论】:

      【解决方案2】:

      我很难理解您的补充细节,但在回答实际问题时:是的,可以扩展 Eloquent 模型。

      <?php
      class User extends \Eloquent {
      
          protected $table = 'users';
      
      }
      
      class Student extends User {
      
          protected $table = 'students';
      
      }
      

      但请注意,任何方法(例如关系、范围等)都会传播到扩展类。如果不希望这样做,则创建一个具有您需要的最少的基类,然后使用您的特定类型对其进行子类化,即StudentAdministrator 等。

      另一种方法是使用接口。因此,如果您知道模型需要相同的属性,但会说,有不同的关系;然后你可以创建一个接口来添加这些约束:

      <?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');
          }
      
      }
      

      【讨论】:

      • 谢谢。如果我不想传播关系和其他,你能解释一下第一个解决方案吗?你告诉我关于基类的事情。但基类是用户类,不是吗?那么区别是什么呢?谢谢
      • 您将有一个基本的User 类,然后您将为更具体的用户类型定义类,它具有您想要的关系和其他东西。
      • 谢谢,但是如果子类的构造函数在另一个表中,我该如何定义它?两个类之间的唯一关系是 sublcas 表中的 user_id 之类的外键
      • 你不需要声明构造函数。您可以像平常一样调用模型,即$students = Student::get()
      • 当然。问题是当超类实例调用与另一个表有关系的子类的方法时,它在查询中使用了错误的外键(超类)。请参阅我的回答中的以下示例。感谢您的耐心等待。
      猜你喜欢
      • 2012-03-13
      • 2011-05-19
      • 2010-10-07
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      • 1970-01-01
      相关资源
      最近更新 更多