Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AbdulBazith's avatar

how to retrieve values from two models with conditions

Guys i have a small correction in my project milkfarm

i have code

  $sales = Sales_details::orderBy('created_at','desc')->get();

      $sales_details = [];

      foreach ($sales as $key => $sale) {
        //total litres initialisation for all customers
        $sales_details[$sale->customer_name]["total_litres"] = 0;
        //total rate initialisation for all customers
        $sales_details[$sale->customer_name]["total"] = 0;
      }



      foreach ($sales as $key => $sale) {
        $sales_details[$sale->customer_name]["total_litres"] += $sale->no_of_litre;
        //sum up the the total rate grouped by customer id
        $sales_details[$sale->customer_name]["total"] += $sale->total;
      }       

     dd($sales_details);

what hapens in this is i have a sales table which possess all the sales entry.

so to sum up all the sales based on total litres of milk and total amount i used this query.

this works fine.

but i have another table received_details

$received=Received_details::orderBy('created_at','desc')->get();

whenever a sales entry is done the amount , balance amount all stored in this received table also for total account.

now whats my problem is.

i have filtrered the total_milk and total litres in sales table.

same as i need to filter the received table also.

simply to say, if i filter just sales table in name Abdul

now $sales will have only sales entry of abdul

like wise i need to take only abdul from the received table.

based on the sales customer name, i need to take received table

for example if i fetch record of 3 persons in $sales only those three persons record must be fetched from the received table also how to do that

if i give like below it fetches all. i need only the persons fetched in $sales

$received=Received_details::orderBy('created_at','desc')->get();

Kindly some one help please

0 likes
2 replies
AbdulBazith's avatar
AbdulBazith
OP
Best Answer
Level 5

found the solution.

what i did is

//First fetched all sales details
 $sales = Sales_details::orderBy('created_at','desc')->get();



// made an array ```$r``` and looped it so that all the names are now stored in ```$r```

 foreach ($sales as $key => $sale)    {

    $r[]=$sale->customer_name;

    }



//atlast now fetched the received details info based on name. used ```whereIn``` fo comapring array values with db

 $received=Received_details::orderBy('created_at','desc')->whereIn('customer_name', $r)->get();


Please or to participate in this conversation.