与我的关系HasMany / BelongsTo的错误

时间:2017-05-15 15:30:34

标签: sql laravel

我有一个模型使用这种关系

$builder->addEventListener(
    FormEvents::POST_SUBMIT,
    function(FormEvent $event) {
      $form= $event->getForm();
      $formData = $form->getData();

      if(! $formData instanceof Departement) {
        //handle this case or just do nothing and return from the listener
        return;           
      }
      // here's the default case
      $this->addVilleField($form->getParent(), $form->getData());

    }
);

具有此关系的模型类型

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

我尝试在我的视图中访问show view以键入但我有很多错误

public function works() { return $this->hasMany('App\Models\Work'); }

我试试这个:Undefined property: Illuminate\Database\Eloquent\Relations\BelongsTo::$name获取数据。

在我的数据库中,我的表'Works'有一个外键'type_id'。

我想得到帖子的“类型”。每个帖子只能有一个。

非常感谢!

3 个答案:

答案 0 :(得分:4)

从语义上讲,你想要建立你的关系:

<强>工作

// A work is of a single type
public function type()
{
    return $this->belongsTo('App\Models\Type');
}

<强>类型

// A type of work can have many items of work
public function works()
{
    return $this->hasMany('App\Models\Work');
}

然后您可以像这样访问关系:

$type = Work::first()->type // return object of type Type
$works = Type::first()->works // return collection of objects of type Work

修改

通过访问与()的关系,您将返回关系的基础查询构建器实例,您需要使用->get()完成语句,如下所示:

$works = Type::first()->works()->get();

答案 1 :(得分:2)

你应该有工作模式:

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

并在您的观点上:

$work->type->name;

答案 2 :(得分:0)

由于您没有使用默认ID作为外键,因此您应该添加

protected $primaryKey = "type_id";

在您的模型中