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 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?