【问题标题】:How to get the latest in this case?在这种情况下如何获得最新信息?
【发布时间】:2020-06-30 18:23:05
【问题描述】:

这对我来说有点难,因为这是我第一次做这种任务,我真的不明白如何查询最新的“消息”。

这是我在控制器中得到的:

    public function show(Group $group)
    {
        return new GroupResource($group->load('messages.user'));
    }

我的逻辑告诉我要执行以下操作:

return new GroupResource($group->load('messages.user')->latest());

但我最终得到了一个错误...Property [id] does not exist on the Eloquent builder instance.

【问题讨论】:

  • 您要限制记录数量吗?因为latest 仅表示基于某些创建时间戳(甚至 id)的降序
  • 我不想限制记录的数量:)
  • 那你的计划是什么?您想按时间戳对附加到组的消息进行排序吗?您需要更具描述性。
  • 是的,按他们的时间戳,从最新到最旧。
  • latest('updated_at'); 试试这个。 updated_at 是字段

标签: laravel


【解决方案1】:

您可以像这样向关系查询添加约束:

return new GroupResource(
    $group->load([
      'messages' => function ($query) {
          return $query->latest();
      },
      'messages.user'
    ])
);

请参阅文档中的Lazy Eager Loading 以供参考。

【讨论】:

  • 应该已经修复了。
  • 现在可能会修复。
  • 是的,没错。这是正确的答案。我很感激! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
  • 2015-05-06
  • 2017-09-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多