Laravel 5加入同桌

时间:2015-08-05 14:26:00

标签: php mysql laravel subquery

您好我需要在一个表中生成两个比较用户,例如我有这个用户具有不同级别的用户

   ID       name          email              level
    -------+-------------+------------------+--------------
   34       Jhon Fus       jhon@jhon.com      1 (Medic)
   35       Michael Chi    mich@jhon.com      2 (Client)

此表存储订单

   ID    client_id   medic_id    status   created_at
    ---+-----------+------------+--------+-------
    1    35          34           ok      2015-07-22 19:34:59
    2    35          34           ok      2015-07-23 19:34:59

预期输出

   order id      cliname    status   **medname**   created
    ---------+-------------+--------+------------+-------
    1          Michael Chi   ok        Jhon Fus   2015-07-22 19:34:59
    2          Michael Chi   ok        Jhon Fus   2015-07-23 19:34:59

我试试这个但是出了点问题:

$orders= Order::join('users', 'users.id', '=', 'orders.client_id')
 ->join('users as usmedics', 'usmedics.id', '=', 'orders.medic_id')
 ->select(array('orders.id', 'users.name as cliname', 'orders.status', 'usmedics.name as medname' , 'orders.created_at'))
 ->orderBy('orders.created_at', 'DESC');

请任意...

1 个答案:

答案 0 :(得分:0)

简单只需编写一个简单的查询:

$sql = "Query as you'd write it normally...";
$result = DB::select( DB::raw($sql));

如果需要,您仍然可以使用绑定:

$sql = "SELECT * FROM tbl1 WHERE user_id = :user_id and thing2 = :thing2";
$sqlBindings=[ 'user_id' => $user_id, 'thing2' => $thing2 ];
$result = DB::select( DB::raw($sql), $sqlBindings);