简体   繁体   中英

Laravel Eloquent - How to define such a relationship: Comment::language()->name

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?

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 :).

Using the belongsTo relationship solved the problem.

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

thanks everyone!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM