使用Laravel查询两个表和两个WHERE条件

时间:2016-06-17 10:08:20

标签: php mysql laravel laravel-4

我有表orders和表payments。我想查询表格orders,加入表格payments并显示订单已付款且未付款。

这是订单型号

class Order extends Eloquent {
     protected $table = 'orders';
     protected $primaryKey = 'order_id';

     public function paidorders() {
         return $this->hasMany('payments', 'processed');
     }
}

这是付款模式

class Payment extends Eloquent {
     protected $table = 'payments';
     protected $primaryKey = 'paymentID';

     public function orders()
     {
         return $this->hasMany('Order', 'user_id');
     }
}

用户模型

public function orders() {
    return $this->hasMany('Order', 'user_id');
}

这就是我目前仅在没有支付/未支付状态的情况下显示订单的方式。

  $orders = self::$user->orders()->get();
     return View::make('site.users.orders', [
        'orders' => $orders
     ]);

这是查询,但我不知道如何在Laravel中实现它

SELECT orders. * , payments. * 
FROM orders
   INNER JOIN payments ON orders.user_id = payments.userID
WHERE orders.user_id =2
AND payments.userID =2

self::$user->...是已登录的用户。如何在WHERE子句中使用它?

我不知道如何构建此查询

更新dd($orders)

object(Illuminate\Database\Eloquent\Collection)#264 (1) { ["items":protected]=> array(1) { [0]=> object(Order)#260 (20) { ["table":protected]=> string(6) "orders" ["primaryKey":protected]=> string(8) "order_id" ["connection":protected]=> NULL ["perPage":protected]=> int(15) ["incrementing"]=> bool(true) ["timestamps"]=> bool(true) ["attributes":protected]=> array(1) { ["processed"]=> string(1) "1" } ["original":protected]=> array(1) { ["processed"]=> string(1) "1" } ["relations":protected]=> array(0) { } ["hidden":protected]=> array(0) { } ["visible":protected]=> array(0) { } ["appends":protected]=> array(0) { } ["fillable":protected]=> array(0) { } ["guarded":protected]=> array(1) { [0]=> string(1) "*" } ["dates":protected]=> array(0) { } ["touches":protected]=> array(0) { } ["observables":protected]=> array(0) { } ["with":protected]=> array(0) { } ["morphClass":protected]=> NULL ["exists"]=> bool(true) } } }

2 个答案:

答案 0 :(得分:4)

Try this query code:-

$users = DB::table('orders')
            ->join('payments', 'orders.user_id', '=', 'payments.userID')
            ->where('orders.user_id', '2')
            ->where('payments.userID', '2')
            ->select('orders.*', 'payments.*')
            ->get();

答案 1 :(得分:1)

$query = Order::select(DB::Raw('payments.processed'))
    ->join('payments', 'orders.order_id', '=', 'payments.orderID')
    ->where('orders.user_id',  2)
    ->where('payments.userID', 2)
    ->get();
相关问题