【问题标题】:Laravel leftJoin ASLaravel 离开加入 AS
【发布时间】:2015-08-09 10:14:27
【问题描述】:

如何在 Laravel Eloquent 或 Fluent 中进行查询?

DUELS
|id|userId1    | UserId2
-------------------------
|1|       1    |  4     |
|2|       3    |  2     |
|3|       2    |  1     |
-------------------------

USERS
|id| firstName | 
----------------
|1|    Bob     |  
|2|    Hans    | 
|3|    Jerome  | 
|3|    Katy    | 
----------------

查询:获取具有$userId的用户参与的决斗中的用户名称:

SELECT u1.firstName AS user1FirstName, u2.firstName AS user2FirstName
    FROM duels             
    LEFT JOIN users AS u1                 
        ON userId1 = u1.id         
    LEFT JOIN users AS u2    
        ON userId2 = u2.id           
    WHERE userId1 = $userId || userId2 = $userId

【问题讨论】:

  • 在这种情况下你能不能有competition,从而知道用户之间的竞争是什么?
  • 对不起,我不明白你的意思。
  • 我提到这是为了确保两个用户之间存在竞争(实际上是决斗)。您是否尝试过我在回答中提到的方法?

标签: php sql laravel eloquent


【解决方案1】:

使用 Laravel 的 Fluent,要执行该查询,您需要执行以下操作:

DB::table('users')->join('duels', function($join) use ($userId){
     $join->on('users.id', '=', 'duels.userId1')
          ->orOn('users.id', '=', 'duels.userId2')
          ->where('users.id', '=', $userId);
})->get();

但是,使用 Laravel 的 Eloquent,您可以将用户视为 第一个玩家,或 第二个玩家。 在您的 User 模型中,这样定义上述两个关系:

     class User extends Eloquent{

        /**
         * ...
         */

         public function duelsAsFirstPlayer(){
             return $this->belongsToMany( 'App\User', 'duels', 'user_id_1', 'user_id_2');
         }

         public function duelsAsSecondPlayer(){
             return $this->belongsToMany( 'App\User', 'duels', 'user_id_2', 'user_id_1');
         }    
     }

现在,为了获得所有与$userId 的用户进行过决斗的用户,查询User 模型:

作为第一个玩家

$users = App\User::find($userId)->duelsAsFirstPlayer()->get();

或作为第二玩家

$users = App\User::find($userId)->duelsAsSecondPlayer()->get();

【讨论】:

  • 感谢您的建议,但我真的很想获得用户参与的所有决斗:)
  • 我认为不可能一次性查询关系的两侧(无论是一对多还是多对多)使用 Eloquent 方法(并以表格形式显示)。因为用户将作为 user 1user 2 参与,所以在查询 Eloquent 关系时必须考虑到这一点。虽然,使用原始查询,您可以将结果显示为映射用户决斗的表格。
猜你喜欢
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-05
  • 2018-10-31
  • 1970-01-01
相关资源
最近更新 更多