【发布时间】:2017-09-07 20:37:28
【问题描述】:
我正在尝试获取用户发布并在帖子下方显示他们的用户名和 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();
【问题讨论】:
-
在您的模型中添加relationship 并执行
Post::with("user")->where...
标签: php mysql laravel laravel-5