简体   繁体   中英

How to write this sql query into laravel eloquent?

I have a query i'm trying to use to optimize my old queries because they weren't efficient enough but I'm having trouble looking for eloquent cheat sheets.

Here is my query:

select * from o inner join t on o.id = t.oid where t.wid in(1,2,3,4)

You must read about relationships

You can do it with a simple relationship:

class Transaction extends Eloquent {
     /**
     * Return the relationship
     **/
     public function order(){
            // The Transaction belongs to Order.
            // So, the Transaction has a order_id reference
            return $this->belongsTo('Order');
     }
}

class Order extends Eloquent {
     /**
     * Return the relationship
     **/
     public function transaction(){
            // Define the relationship. Order has one Transaction
            // So, the table Transaction has a order_id reference.
            return $this->hasOne('Transaction');
     }
}

/**
/* In your controller:
**/
// Return the Transaction where id is 1, 2, 3 or 4.
$transaction = Transaction::whereIn('waypoint_id', array(1,2,3,4) )->get();
// Get the Order owner of the Transaction
$order = $transaction->order;

echo $order->id; // It prints the Order id
echo $transaction->id; // It prints the Transaction id

Also you can get the Transaction from a Order so:

$order = Order::find(1); // Get the order with id 1
$transaction = $order->transaction; // Get the transaction 

Try this

$output = DB::table('orders as od')
        ->join('transactions as tr', 'od.id', '=', 'tr.order_id')
        ->whereIn('tr.waypoint_id', array(1,2,3,4))
        ->get();

print_r($output);   // it will return an array of object

reference: http://laravel.com/docs/queries#joins

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM