doutuobao9736 2017-07-15 08:13
浏览 32
已采纳

如何在laravel中创建获取帖子及其用户详细信息的查询

I'm trying to fetch users Post and display their username & id below the post how can i create such query

Here is my Post Table

  ---------------------------------------------------------------------
  | 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 |
  ---------------------------------------------------------------------

User table

  ------------------------------------------------------------
  | 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 |
  ------------------------------------------------------------

Now I would like to fetch all post from database and fetch from users table - name,img,username etc...

Here is what my query looks like till now

$p1 = App\Models\Post::where('status', 'active')
            ->orderBy('id', 'desc')
            ->take(6)
            ->get();
  • 写回答

2条回答 默认 最新

  • doupu1957 2017-07-15 08:32
    关注

    Try this... i used only JOIN because every post has a user.... you can refer this link 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();
    

    Try this for category just what you need to select just add it in select clause...

    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条)

报告相同问题?

悬赏问题

  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思