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 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码