sql - LARAVEL:返回所有帖子的最后评论基于当前登录用户
问题描述
查询 GET all POST 的 USER
$result = DB::table('tasks as t')->select('*' , 't.created_by as task_creator' , 't.task_id as task_id' , 't.created_at as task_created')
->join('task_assign as ta', 'ta.task_id', '=', 't.task_id')
->join('users as u' , 'u.id' , '=' , 't.created_by')
->join('task_categories as tcc' , 'tcc.category_id' , '=' , 't.category_id')
->leftJoin('task_comments as tc' , 'tc.task_id' , '=' , 't.task_id')
->where("ta.user_id" , Auth::user()->id)
->where("t.status" , 'A')
->where("t.task_status" , '!=' , 'D')
->orderBy('tc.date_added' ,'DESC')
->orderBy('t.task_id' ,'DESC')
->get();
获取用户最后评论的所有帖子
# SET STATUS BASED ON USERS
$c = [];
$group = [];
foreach ($newArray as $key => $row) {
# check if user is the last comment
$check = DB::table('task_comments as tc')->select('*')
->where("tc.task_id" , $row->task_id)
->orderBy('tc.task_comments_id' ,'DESC')
->get()->first();
if (!empty($check)) {
if ($check->user_id == Auth::user()->id) {
$c[] = $check->user_id;
$group['I'][$key] = $row;
}
}
}
如果发布最后一条评论是当前登录用户,他们是我可以删除循环并获取所有帖子的一种方式。
解决方案
我使用的是 QueryBuilder 宏。将此脚本添加到您的app/Providers/AppServiceProvider.php
/**
* Register any application services.
*
* @return void
*/
public function register()
{
Builder::macro('whereLatest', function ($table, $parentRelatedColumn) {
return $this->where($table . '.id', function ($sub) use ($table, $parentRelatedColumn) {
$sub->select('id')
->from($table . ' AS t1')
->whereColumn('t1.' . $parentRelatedColumn, $table . '.' . $parentRelatedColumn)
->latest()
->take(1);
});
});
}
比你可以使用:
Auth::user()->whereHas('posts', function($q) {
$q->whereLatest('posts_table_name', 'user_id');
});
推荐阅读
- python - Django Rest Framework 模型对象返回带有选项的字段的存储值
- javascript - 在 graphql 的解析器中获取用户代理访问权限
- android - 是否可以为单个类提供多个委托类型?
- javascript - 使用一些 JS 框架的可重用组件或小部件
- codenameone - TextArea 不允许根据需要输入文本
- python - 在 Python 中通过 REST API 传递 mongodb 查询
- excel - Application.Goto 运行时错误 5
- maven - 带有 JPA 的 Java 10 的 Maven 依赖项(eclipse 链接和休眠)
- angular - Angular 5 Asp.net Core CloudFlare SSL - 浏览器后退按钮故障
- java - Java EE - 返回 415 状态