1
votes

The languages table has: id, shortcode

The comments table has id, user_id, comment, language_id (foreign key)

In the Comment Model I defined Language as a hasOne Relationship

In the Language Model I defined Comments as a hasMany Relationship (this is wrong?).

In Tinker I get this error when I try to execute: $comment->language()->get():

Column not found: 1054 Unknown column 'languages.comment_id' in 'where clause' (SQL: select * from `languages` where `languages`.`comment_id` = 7 and `languages`.`comment_id` is not null)'

Why is Laravel searching in the languages table for the comment_id? It seems I misunderstand something completely.

What is the right way to do get the language shortcode? I thought $comment->language()->shortcode should work.

And what is the most efficient way to preload all the language_id and shortcode information without performing duplicate queries since this is used a lot?

2
The comment model should have a belongsTo relationship, not hasOne. Also, the tables should be named comments and languages, not comment and language. - Joel Hinz

2 Answers

2
votes

Laravel makes assumptions on your key-names in your relationship. Because you use the hasOne relationship, Laravel expects the key to be in the languages table, named comment_id.

Your Comment model should use a belongsTo relationship to Language and drop the hasOne. This way laravel makes the assumption that the foreign-key is actually in the comments table, named language_id, which is the case :).

1
votes

Using the belongsTo relationship solved the problem.

Afterwards I could access it with $comment->language->shortcode;

thanks everyone!