【问题标题】:Laravel Error while creating a pivot model创建数据透视模型时出现 Laravel 错误
【发布时间】:2015-06-17 18:32:39
【问题描述】:

我有以下模型和关系:

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

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

【问题讨论】:

    标签: model laravel-5 pivot-table


    【解决方案1】:

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

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

    【讨论】:

    • 这是一个问题。谢谢你找到那个。然而,这并没有解决问题。我已经更新了我的问题中的代码。
    【解决方案2】:

    我终于找到了。

    有 2 个问题。

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

    如:

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

    例如在 Fence 模型中:

     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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多