doufeng9567 2016-10-17 16:36
浏览 58
已采纳

Laravel Mysql从两个表中选择并在第三个表上连接结果

I wonder if its possible to select two tables and join a third table

I have 3 tables:

upvotes -id (PK) -voteOn (FK) - points to users PK -voteBy (FK) - points to users PK -vote (Int) -voteAdded (Int) - unix timestamp

downvotes -id (PK) -voteOn (FK) - points to users PK -voteBy (FK) - points to users PK -vote (tinyInteger) -voteAdded (Int) - unix timestamp

users id (PK) username

What I now want to do is ~ select ALL votes from the tables upvotes and downvotes where voteOn = 2 then join table users on voteBy orderBy voteAdded Asc

More or less I want to get all votes on a specific user then join the users table so that I can get the username of the person who placed the vote

  • 写回答

1条回答 默认 最新

  • dqiatvbi61502 2016-10-17 18:37
    关注

    U can use the DB facade to achieve this which will generate an sql query that is fired on the db

      $users = DB::table("users AS a") 
                       ->select(array("a.id as user_id", "a.username", "b.voteOn as upvote_on",
                    "b.vote as upvote", "b.voteAdded as upvote_added","c.voteOn as downvote_on",  "c.vote as downvote",
                      "c.voteAdded as downvote_added"))
                       ->join("upvotes AS b",  "a.id", "=", "b.voteBy")
                       ->join("downvotes AS c",  "a.id", "=", "c.voteBy")
                       ->orderBy("b.voteAdded", "asc") 
                       ->get();
    

    Then you can loop through the users using foreach

       foreach($users as $user) {
          $user->user_id;
          //use the alias as used in the select chained function 
        } 
    

    That should work

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料