dongpu1908 2016-06-17 10:08
浏览 303
已采纳

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

I have table orders and table payments. I want to query table orders, joining table payments and to show with an order is paid and which isn't.

This is Order model

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

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

This is Payment model

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

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

And the User model

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

This is how I show currently orders only without status paid/not paid.

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

This is the query but I don't know how to implement it in 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->... is the logged user. How will be used this in the WHERE clause?

I don't get it exactly how to build this query

UPDATE 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条回答 默认 最新

  • dpa84373 2016-06-17 10:35
    关注
    $query = Order::select(DB::Raw('payments.processed'))
        ->join('payments', 'orders.order_id', '=', 'payments.orderID')
        ->where('orders.user_id',  2)
        ->where('payments.userID', 2)
        ->get();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题