【发布时间】:2021-02-02 03:08:45
【问题描述】:
好久不见:D
最近,我一直在尝试开发一个网站,但似乎没有找到解决方案。已经3周了,我还做不到。 我没有使用模型,因为我仍然没有像我想要的那样理解它们,也许像 hasmany 或 belongsto 这样的东西会有所作为,但我不知道如何使用它们
这是查询:
$threads = DB::table('threads')
->join('users as author', 'author.id', '=', 'threads.user_id')
->join('replies', 'replies.thread_id', '=', 'threads.id')
->join('categories', 'categories.id', '=', 'threads.category_id')
->join('users as users', 'users.id', '=', 'replies.user_id')
->select('threads.id as thread_id','threads.category_id as thread_category','threads.title as thread_title', 'replies.body as thread_first_message', 'author.name as thread_author', 'author.id as author_id', 'replies.created_at as last_reply_date', 'users.name as last_reply_user', 'users.id as lru_id', 'threads.visits', 'threads.hd', 'threads.18', 'threads.prv', DB::raw('(SELECT COUNT(id) FROM replies WHERE thread_id = threads.id) as count_replies'))
->where('replies.created_at', '=', DB::raw('(SELECT max(created_at) FROM replies)'));
我需要从 3 个表中获取多个数据。
我将解释每一列的内容:
thread_id:来自表'threads'的字段(id)
thread_category:来自“threads”的字段(category_id)和来自表“categories”(id)的外键
thread_title:来自“线程”的字段(标题)
thread_first_message:第一个字段(正文)来自表 'replies' where thread_id = (thread_id)
thread_author:来自“threads”的字段(user_id)和来自表“users”的foregin key(id)
author_id:来自撰写第一条消息的“用户”的字段 (id)
last_reply_date:来自 'replies' 的字段 (created_at) 其中 'replies.id' = (thread_id)
last_reply_users:来自在 (thread_id) 中写入最后一条消息的“用户”的字段(名称)
lru_id:字段 (id) 来自 'users' 来自 'users',最后一条消息写在 (thread_id)
visits:来自表“线程”的字段(访问)
hd, prv, 18:来自表“线程”的布尔字段(它们在这里无关紧要,也许在未来)
count_replies:所有回复的总和,其中 thread_id = (thread_id)
数据库现在看起来像这样:
我的问题是我在数据库中有2条记录,所以页面中应该显示2个div,但只显示一个:
我得到的结果:
我需要的结果:
因为threads表有2条记录:
你们能给我一些帮助吗?提前谢谢你
编辑:我到这里为止:
SELECT DISTINCT(t.id), t.category_id, t.title, r1.body, u1.name as author, u1.id, r2.created_at, u2.id as last_author_id, u2.name as last_author, t.visits, COUNT(DISTINCT(r3.id)) from threads t, replies r1, replies r2, replies r3, users u1, users u2 where r1.thread_id = t.id and u1.id = t.user_id and r2.thread_id = t.id and r2.user_id = u2.id and r3.thread_id = t.id group by t.id
它检索到这个:
我不知道如何将其转换为 Eloquent Query 或者它是否最佳
【问题讨论】:
-
如果是我,我会从sql开始。
-
我只得到 1 个结果,但会有 2 个结果,因为我的数据库有 2 个线程记录
-
这里没有“记录”。只有 ERD 的图片
标签: mysql database laravel model-view-controller eloquent