Php 如何在laravel中创建查询,以获取帖子及其用户详细信息
我正在尝试获取用户的帖子,并在帖子下方显示他们的用户名和id。如何创建这样的查询 这是我的邮政桌Php 如何在laravel中创建查询,以获取帖子及其用户详细信息,php,mysql,laravel,laravel-5,Php,Mysql,Laravel,Laravel 5,我正在尝试获取用户的帖子,并在帖子下方显示他们的用户名和id。如何创建这样的查询 这是我的邮政桌 --------------------------------------------------------------------- | id | user_id | title | content | status | time | | 1 | 2 | example | Something | active | 2017-07
---------------------------------------------------------------------
| 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();
使用laravel查询生成器 像这样试试
$result = DB::table('users')
->leftJoin('post', function ($join) {
$join->on('users.id', '=', 'post.user_id');
})
->orderBy('users.id', 'desc')
->get();
试试这个。。。我只使用JOIN,因为每个帖子都有一个用户。。。。 你可以参考这个链接 请尝试将此类别作为您需要选择的类别,只需将其添加到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();
在您的模型中添加一个,然后执行
Post::with(“user”)->在哪里…
是否有任何方法也可以获取类别?有一个具有id和post_id的类别表。
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();