Laravel 4 --JOINS--组合两个表以检索条目中多个代理的名称

时间:2014-01-01 18:02:46

标签: laravel laravel-4

我需要Laravel 4加入声明。

下面的图片描绘了我拥有的两张桌子和我需要的桌子。

enter image description here

我需要使用这两个表来检索用户A和用户B的名称。

2 个答案:

答案 0 :(得分:0)

$trades=  DB::select("select trades.id, u.userA_user_name, uu.userB_user_name, trades.time, trades.currency  

    from trades 

    left join 
        (
           select id, user_name as `userA_user_name` from users
         ) u on u.id = trades.userA

    left join 
         (
              select id, user_name as `userB_user_name` from users
          ) uu on uu.id = trades.userB");

如果您需要绑定参数:

 $trade=  DB::select("select trades.id, u.userA_user_name, uu.userB_user_name, trades.time, trades.currency  

        from trades 

        left join 
            (
               select id, user_name as `userA_user_name` from users
             ) u on u.id = trades.userA

        left join 
             (
                  select id, user_name as `userB_user_name` from users
              ) uu on uu.id = trades.userB

        where trades.id = ?", array(20));

答案 1 :(得分:0)

这样的事情可能会有所帮助:

$query = new User; // Your model name. (tablename = users)
$query = $query->join('trades', 'users.trade_id', '=', 'trades.id');

$query = $query->where('users.mail', '=', 'some@mail'); // not necessarily
$query = $query->where('trades.userA', '=', 'some_user'); // not necessarily

$result = $query->orderBy('created_at', 'DESC')->paginate(5); // or $query->get();