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 这个复选框什么作用?
  • ¥15 单通道放大电路的工作原理
  • ¥30 YOLO检测微调结果p为1
  • ¥20 求快手直播间榜单匿名采集ID用户名简单能学会的
  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决