Laravel 创建数据透视模型时出错

Laravel Error while creating a pivot model

我有以下模型和关系:

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 将 return 为 null 或 false(当您尝试实例化某些非存在)。

我终于找到了。

有 2 个问题。

  1. 您不应直接在模型中创建与枢轴模型的关系,而应定义与通过枢轴模型的对立模型的关系。

如:

class Fence extends Model {
    public function fencePoints(){
        return $this->hasMany('App\Models\FencePoint');
    }
    ...
}
  1. 我在Models上定义的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;