-1

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?

Rwd
  • 34,180
  • 6
  • 64
  • 78
nikubik
  • 21
  • 7
  • 2
    If you want relation 1 to 1 between author and article, you should do it like this: in author: `public function article() { return $this->hasOne(Article::class); }` and in article: `public function author() { return $this->belongsTo(Author::class); }` https://laravel.com/docs/9.x/eloquent-relationships#one-to-one – ericmp Sep 13 '22 at 14:40
  • I found it, almost your solution. In Author i use hasMany, since an author might have written many articles. Thank you. – nikubik Sep 13 '22 at 14:43
  • 2
    if Author has many articles, then is not 1 to 1, is 1 to N!! one to many – ericmp Sep 13 '22 at 14:52
  • 1 to 1 in that approach is in my opinion useless. It's because the specific author cannot have more than one articles assigned. You should think about changing it to one to many relationship or stay with your idea if you really want to have a little bit "locked" . – kalview Sep 13 '22 at 22:28

1 Answers1

0

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.

kjoedion
  • 562
  • 1
  • 8