Home > database >  query db laravel return one result with dynamic condition
query db laravel return one result with dynamic condition

Time:10-01

what I'm trying to do is remove the bikes that have contracts and only view the ones that are available

I take the required dates from ajax and pass them to the controller

    public function checkBike(Request $request){
        //i get the dates from ajax
        $date1=Carbon::parse($request->start)->format('Y-m-d');
        $date2=Carbon::parse($request->end)->format('Y-m-d');
        
        
        $contract=DB::table('contracts')->get();
        //filter contracts whose start date and end date are the dates received from ajax
        $contractdate=DB::table('contracts')->whereRaw('? between data_inizio and data_fine', [$date1,$date2])->get();

        if (count($contractdate) > 0) {

            //cycle the contracts I found with the dates entered
            foreach ($contractdate as $cdate) {
                //I get the contract id 
                $idcontract=$cdate->id; 
                //I search the database for all the bikes associated with that contract
                $bikecontract=DB::table('bike_contract')->where('contract_id','=',$idcontract)->select('bike_id')->get();
                
            }
            //cycle the ids of the bikes associated with the contract I just found
            
            for ($i=0; $i < count($bikecontract); $i  ) { 
                $bikeid[$i]=$bikecontract[$i]->bike_id;
            }
            $bikecorrect=DB::table('bikes')->orWhere('id','!=',$bikeid)->get(); 
            //in this dynamic query the result I have is the exclusion of only one bike, when it should exclude all the ids that go from $ bikeid[$i]

            
            

            

            return response()->json(["qty"=>$bikecorrect]);
}

the problem is that the query removes only one bike of the two found

if I log $ bikeid, the result is the following:

{qty: Array(2)}
qty: Array(2)
0: 2
1: 5
length: 2
[[Prototype]]: Array(0)
[[Prototype]]: Object

2 and 5 are the ids I need to remove, instead the query only removes one.

Where am I doing wrong?

CodePudding user response:

You need to change your query:

$bikecorrect=DB::table('bikes')->whereNotIn('id', $bikeid)->get(); 

Make sure $bikeid is an array of bike ids.

  • Related