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

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

报告相同问题?

悬赏问题

  • ¥15 怎样才能让鼠标沿着线条的中心线轨迹移动
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?