创建枢轴模型时Laravel错误

时间:2015-06-17 18:32:40

标签: model laravel-5 pivot-table

我有以下模特和关系:

class Fence extends Model {
    public function fenceLines(){
        return $this->hasMany('App\Models\FenceLine');
    }

    public function newPivot(Model $parent, array $attributes, $table, $exists){
        if ($parent instanceof FenceLine) {
            return new FenceLine($parent, $attributes, $table, $exists);
        }
        return parent::newPivot($parent, $attributes, $table, $exists);
    }
}

class FencePoint extends Model {
    public function fenceLines(){
        return $this->hasMany('App\Models\FenceLine');
    }

    public function newPivot(Model $parent, array $attributes, $table, $exists){
        if ($parent instanceof FenceLine) {
            return new FenceLine($parent, $attributes, $table, $exists);
        }
        return parent::newPivot($parent, $attributes, $table, $exists);
    }
}

class FenceLine extends Pivot {
    protected $table = 'fences_fence_points';
    public function fence(){
        return $this->belongsTo('App\Models\Fence');
    }

    public function fencePoint(){
        return $this->belongsTo('App\Models\FencePoint');
    }
}

当我致电$fence->fenceLines()时,我收到以下错误:

Argument 1 passed to App\Models\Fence::newPivot() must be an 
instance of Illuminate\Database\Eloquent\Model, none given

我已经阅读了很多关于这个问题的博客,我找不到任何解决方案。

2 个答案:

答案 0 :(得分:1)

如果我没弄错的话,它看起来像一个简单的语法错误;当它们应该是反斜杠时,你使用普通斜线。 hasMany($related, $foreignKey = null, $localKey = null)期望您提供相关模型的命名空间路径,而不是目录(以便$instance = new $related可以正确执行)。

因此,当您尝试实例化一个新的hasMany对象时,您会失败,因为new App/Models/FenceLine将返回null或false(当您尝试实例化不存在的东西时,不确定该值是什么)。

答案 1 :(得分:1)

我终于找到了它。

有2个问题。

  1. 您不应直接在模型中创建与Pivot模型的关系,而应定义与通过数据透视模型的对立模型的关系。
  2. 如:

    class Fence extends Model {
        public function fencePoints(){
            return $this->hasMany('App\Models\FencePoint');
        }
        ...
    }
    
    1. 我在模型上定义的newPivot函数是错误的。您应该使用相反的模型,而不是在调用instanceof中使用Pivot模型。
    2. 如Fence Model:

       public function newPivot(Model $parent, array $attributes, $table, $exists){
           if ($parent instanceof FencePoint) {
               return new FenceLine($parent, $attributes, $table, $exists);
           }
      

      在FencePoint模型中:

      public function newPivot(Model $parent, array $attributes, $table, $exists){
          if ($parent instanceof Fence) {
              return new FenceLine($parent, $attributes, $table, $exists);
          }
      

      然后您可以使用枢轴模型,例如:

      $fence = Fence::find(1);
      $fencePoint = $fence->fencePoints->first();
      $fenceLine = $fencePoint->pivot;
      
相关问题