我试图获取用户发布并显示其用户名&在帖子下面的id如何创建这样的查询
这是我的帖子表
---------------------------------------------------------------------
| id | user_id | title | content | status | time |
| 1 | 2 | example | Something | active | 2017-07-11 13:48:26 |
| 2 | 2 | example | Something | active | 2017-07-11 13:48:26 |
| 3 | 3 | example | Something | active | 2017-07-11 13:48:26 |
| 4 | 4 | example | Something | active | 2017-07-11 13:48:26 |
| 5 | 5 | example | Something | active | 2017-07-11 13:48:26 |
---------------------------------------------------------------------
用户表
------------------------------------------------------------
| id | name |password | img | last_login |
| 1 | User1 | example | Something | 2017-07-11 13:48:26 |
| 2 | User2 | example | Something | 2017-07-11 13:48:26 |
| 3 | User3 | example | Something | 2017-07-11 13:48:26 |
| 4 | User4 | example | Something | 2017-07-11 13:48:26 |
| 5 | User5 | example | Something | 2017-07-11 13:48:26 |
------------------------------------------------------------
现在我想从数据库中获取所有帖子并从用户表中获取 - 名称,img,用户名等......
这是我的查询到目前为止的样子
$p1 = App\Models\Post::where('status', 'active')
->orderBy('id', 'desc')
->take(6)
->get();
答案 0 :(得分:2)
试试这个...我只使用JOIN,因为每个帖子都有一个用户.... 您可以参考此链接https://laravel.com/docs/5.4/queries#joins
DB::table('post')
->select('post.*','user.id','user.name')
->join('user','user.id','=','post.user_id')
->get();
尝试将此类别用于选择只需将其添加到select子句中的类别...
DB::table('post')
->select('post.*','user.id','user.name', 'category.*')
->join('user','user.id','=','post.user_id')
->join('category','post.id','=','category.post_id')
->get();
答案 1 :(得分:1)
使用laravel查询构建器
试试这个
Address