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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题