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 Matlab在app上输入带有矩阵形式的初始条件发生错误
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器