【问题标题】:Laravel join table using eloquentLaravel 使用 eloquent 连接表
【发布时间】:2018-11-06 08:25:35
【问题描述】:

我正在尝试加载最后 5 个相关帖子的 cmets,仅从帖子中选择 id 和标题。

在第一种情况下,我决定从帖子中获取所有列:

Comment::with(['post'])->take(5)->orderBy('id', 'desc')->get();

而且它运行良好。

但是当我尝试只获取两列(“id,title”)时,帖子中的任何内容都不会加载。

Comment::with(['post:id,title'])->take($number)->orderBy('id', 'desc')->get();

我做了一个测试,当我删除“orderBy('id', 'desc')”时又好了。

Comment::with(['post:id,title'])->take($number)->get();

所以“orderBy”选项肯定有问题。

有什么办法可以解决吗?这意味着只从“posts”表中获取选定的列,并从最后一个中获取结果?

谢谢。

【问题讨论】:

  • 您需要通过id 来说明您要订购什么。 id 的帖子或 id 的评论。
  • 为什么不通过 id 获取帖子,然后获取所有 cmets?
  • @MaihanNijat 因为任务是获取last cmets

标签: php laravel


【解决方案1】:

由于你的 Comment 和 Post 模型都包含 id,Laravel 不知道你想按哪一个排序。所以,给你的orderBy添加一个表名:

Comment::with(['post:id,title'])->take($number)->orderBy('comments.id', 'desc')->get();

这里comments 是您的表/实体的名称,可能是comment

【讨论】:

  • 谢谢。现在对我来说很明显:D。
猜你喜欢
  • 2019-09-06
  • 2018-08-07
  • 2019-12-06
  • 2021-01-05
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 2020-11-06
  • 2015-09-06
相关资源
最近更新 更多