dongziya9863 2016-05-14 10:46
浏览 122
已采纳

使用findOrFail()的Laravel急切加载问题

Why to I get multiple results for this? I just want the "contacts" for the given client id. Not for all clients.

public function edit($id)
{
    $client = Client::findOrFail($id)->with('contacts')->get();
}

Thanks,

  • 写回答

1条回答 默认 最新

  • douyimiao1993 2016-05-14 10:55
    关注

    Basically, findOrFail() finds a single result for you instead of returning a collection. What that means is that it already does a get() call for you. So you can't add another get() after that. If you do, you'll get weird results as you noticed because you're essentially building a new query.

    That also means that you don't need to eager load anything. The reason eager loading is good is because it allows you to fetch data for multiple objects in a single query. But you only have one object here anyway - so it doesn't really matter.

    You could easily do just $client = Client::findOrFail($id); and then $client->contacts later, when you need the contacts. It won't make your performance worse.

    And if you only want the contacts, not the client, you could easily do this: $client = Client::findOrFail($id)->contacts;

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

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式