Can't get a one-to-one relation working in Laravel

Viewed 39

I try to get the Author of an Article, which is a One-To-One relation, but i can't get it. My foreign key author_id is in the Article.

MCD

So i define in my Article Model the relation :

public function author() {
  return $this->hasOne(Author::class);
}

Same in my Author Model :

public function article() {
  return $this->belongsToMany(Article::class);
}

But i got this error:

SQLSTATE[42S22]: Column not found: 1054 Champ 'authors.article_id' inconnu dans where clause

It seems like it tries in the wrong way, looking for an article foreign key in the author table.

I tried to reverse the relations, but this time it looks for a pivot table.

I don't know how to map the relation the right way. Any idea?

1 Answers

The relationship in your Author model should be:

public function articles() {
  return $this->hasMany(Article::class);
}

The relationship in your Article model should be:

public function author() {
  return $this->belongsTo(Author::class);
}

Your articles table should have an author_id integer column.

Related