Model 创建轴模型时发生拉威尔错误

Model 创建轴模型时发生拉威尔错误,model,laravel-5,pivot-table,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

我有以下模型和关系:

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

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

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

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

我最终找到了它

有两个问题

  • 您不应该直接在模型中创建与轴心模型的关系,而应该定义与通过轴心模型的对立模型的关系
  • 例如:

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

     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;
    

    这是一个问题。谢谢你找到那个。然而,这并没有解决问题。此后,我更新了问题中的代码。