[英]How to create a query in laravel which fetch post and its user detail
我正在嘗試獲取用戶帖子,並在帖子下方顯示其用戶名和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();
試試這個...我只用了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();
通過使用laravel查詢構建器
這樣嘗試
$result = DB::table('users')
->leftJoin('post', function ($join) {
$join->on('users.id', '=', 'post.user_id');
})
->orderBy('users.id', 'desc')
->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.