我有以下模特和关系:
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
我已经阅读了很多关于这个问题的博客,我找不到任何解决方案。
答案 0 :(得分:1)
如果我没弄错的话,它看起来像一个简单的语法错误;当它们应该是反斜杠时,你使用普通斜线。 hasMany($related, $foreignKey = null, $localKey = null)
期望您提供相关模型的命名空间路径,而不是目录(以便$instance = new $related
可以正确执行)。
因此,当您尝试实例化一个新的hasMany对象时,您会失败,因为new App/Models/FenceLine
将返回null或false(当您尝试实例化不存在的东西时,不确定该值是什么)。
答案 1 :(得分:1)
我终于找到了它。
有2个问题。
如:
class Fence extends Model {
public function fencePoints(){
return $this->hasMany('App\Models\FencePoint');
}
...
}
如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;