douweida2669 2018-12-04 11:01
浏览 47
已采纳

Laravel Eloquent - 通过它的Y列获取所有X.

Let's say I have a Thread model, which hasMany Post. I want to get all Post that belongs to a certain thread.

However the query params sent to the controller is not id, but is the 'thread_name' of the Thread.

What I'm doing right now is something like this:

1) Get the thread by thread_name (for argument sake, it's unique), which will give me $thread
2) Get all post where thread_id = $thread->id

I think this is not efficient because I'm sending doing two SQL queries.

Is there anyway to select the post through thread_name?

I'm sorry, I think this thread's title is quite confusing.

  • 写回答

1条回答 默认 最新

  • drm16022 2018-12-04 11:07
    关注

    You should try this:

    $thread = Thread::where('thread_name', $thread_name)->with('posts')->first();
    

    This will load the posts of the thread into the Thread object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?