Home > other >  What is the method of querying from two tables with a condition in Laravel?
What is the method of querying from two tables with a condition in Laravel?

Time:05-06

I have an invoice table and a detail table in the database and they have a relationship What is the best way to query from two tables? Provided that the invoice is of type 1 or 2

this code

    $Details = Invoice_Details::with(['invoice' => function($q){
        $q -> where('Invoice_type', 1);
    }]) -> with('invoice') -> get();

    return $Details -> sum('quantity');

Thank you

CodePudding user response:

Laravel have very detailed documentation. You just have to browse the documentation site: https://laravel.com/docs.

Your question can be solved using these docs:

CodePudding user response:

I hope that invoice type is dynamically send by request on this situation you can use query builder for that. in your case i think it may suit for you

 $query = Invoice_Details::query()-> with('invoice');
          
        
         if($request->invoice_type==1){

              $query->whereRelation('invoice','Invoice_type','=' ,1);
           }

    $Details = $query->get();

    return $Details -> sum('quantity'); 

i hope it helps you

  • Related