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.

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

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?