【问题标题】:Inheritance in LaravelLaravel 中的继承
【发布时间】:2014-08-01 12:32:32
【问题描述】:

我有两节课。 A 和 B。A 类扩展了 Laravel,B 类扩展了 A。 他们说唱两张桌子。与 B 类关联的表没有主键,也没有外键 (A_id)。情况是这样的:

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

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

我需要在 B 类中指定主键,因为 laravel 尝试使用构建 B 对象

 SELECT * FROM B where id = ?

但字段 id 不存在。

问题是当我尝试从 B 对象 es 访问 A 方法时

$b = B::find(1);
$b->method_in_a_class();

调用的方法在 C 表(也是另一个类)中执行查询,与 A 表链接,而不是与 B 表链接,因此框架执行此查询:

SELECT * FROM C WHERE B_id = ?

但它会是

SELECT * FROM C WHERE A_id = ?

为什么??

谢谢

【问题讨论】:

    标签: php inheritance laravel-4 eloquent models


    【解决方案1】:

    可能最简单的解决问题的方法是使用一对一的关系,这样你就有了:

    class A extends Eloquent 
    {
       protected $table  = 'a';
    
       public function b()
       {
            return $this->hasOne('B');
       }
    }
    
    class B extends Eloquent
    {
       protected $table  = 'b';
    
       public function a()
       {
            return $this->belongsTo('A');
       }
    }
    

    希望这能解决您的问题!

    【讨论】:

    • 这是一种解决方案。但不是最好的,原因有两个:1)从逻辑上讲,它不是一回事 2)我不能直接从 B 实例访问 A 方法。
    【解决方案2】:

    如果第二个表中没有主键,则应考虑合并表。如果没有主 ID,无论如何您都无法将其用作 Eloquent 模型。您遇到这个问题可能是因为数据库设计不好。

    【讨论】:

      【解决方案3】:

      首先,回答您的问题:Eloquent 使用 B 名称作为外键,因为您没有告诉它不要这样做。

      想象一下这个场景(不完全像你的,但它是真实的):帖子模型、类别模型、RootCategory 模型:

      class Category extends \Eloquent {
        public function posts()
        {
          return $this->hasMany('Post');
        }
      }
      
      // categories are hierarchical, self referencing table
      class RootCategory extends Category {
        // global scope and stuff
        protected $table = 'categories';
      }
      
      class Post extends \Eloquent {
        public function category()
        {
          return $this->belongsTo('Category');
        }
      }
      

      现在,通过上述设置,调用简单的动态属性将抛出 - column not found 'posts.root_category_id' 这可能就是您的情况。

      原因如下:

      1. 您没有指定要查找的外键...
      2. ...所以 Eloquent 调用通用的getForeignKey() 方法来猜测它

      getForeignKey()使用$this,即RootCategory对象,所以外键为root_category_id


      所以有两种方法可以解决这个问题:

      1 更好

      // RootCategory model
      public function getForeignKey()
      {
        return 'category_id';
      }
      

      2 也可以,但是需要编辑父类。

      // Category model
      public function posts()
      {
        return $this->hasMany('Post', 'category_id');
      }
      

      【讨论】:

        猜你喜欢
        • 2016-02-01
        • 2014-07-21
        • 2014-09-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-04-04
        • 1970-01-01
        相关资源
        最近更新 更多