spoon
4 years ago
858
4
Laravel

hasMany foreign key and local key

Posted 4 years ago by spoon

Hi, I'm confused about hasMany.

I have a model called Thing. A thing can have many comments and a comment belongs to a thing, I got it.

thing table

thing_id
original_name

thing_comment table

comment_id
thing_id (foreign key from thing table)
comment
created_at
updated_at

Here's what I have now. Thing model

    public function comment()
    {
        return $this->hasMany('\App\Models\ThingComment','thing_id');
    }

ThingComment model

    public function commentThing() {
        return $this->belongsTo('\App\Models\Thing','thing_id');
    }

My test script is below and it works without an issue, but the Laravel docs says that you need to put your foreign key first, then local key. If I add local key (comment_id) after thing_id in the Thing model, I only get a white, blank page.

Why does it happen?

Route::get('comments', function() {
    $comments = App\Models\Thing::find(100120)->comment;
    foreach ($comments as $comment) {
        echo $comment->comment;
    }
});

Please sign in or create an account to participate in this conversation.