egekhter
egekhter

Reputation: 2225

Laravel eloquent efficiency

I have a Laravel 4 app with three tables in question: a client table, an order table with client_id column, and an order_outputs table with an order_id column.

My question is whether the following code is efficient enough for what I'm trying to do, which is find whether the logged in user has ordered a specific output_id . Best practices would be highly appreciated.

   public function getEdit($id) {

      $order = ShopOrder::find($id);

      $client = ShopClient::find($order->client_id);
      $clientorders = ShopOrder::where('client_id', $client->id)->get();

      $orderlist =array();
      foreach ($clientorders as $co)
      {
          $orderlist[] =($co->id);
      }

      $orderoutputs = ShopOrderoutput::whereIn('order_id',$orderlist)->where('output_id', '22')->get();
      $orderoutputslist = array();
      foreach ($orderoutputs as $list)
      {
         $orderoutputslist[] = $list->output_id;
      }


     if (in_array(22, $orderoutputslist))
     {
        echo 'finally';
     } 
}

Thanks.

Upvotes: 0

Views: 664

Answers (1)

Loopo
Loopo

Reputation: 2195

If all you want to do is find out whether the user has an order with a specific output_id, I would combine the queries into one Joined query.

I assume that the order_outputs table is related to the order_outputs table, by a foreign key order_id.

I am also assuming that you are trying to find if the client/user has ever had an order with order_output output_id = 22

I'm not familiar with the syntax for the db queries in laravel.

In plain SQL this would be.

SELECT id FROM orders 
    INNER JOIN order_output ON order.id = order_output.order_id
    INNER JOIN clients on order.client_id = client.id
  WHERE client.id = $client_id
    AND order_output.output_id = 22;

Then count your result set and see if there is at least one.

This way your database engine will do the work for you instead of your php code having to loop through result sets.

Upvotes: 2

Related Questions