lundi 10 septembre 2018

Laravel Where In on Where Has

Is there any way to return a parent model with a relationship but only return some of the relationship rows by using a where in?

That may be quite confusing, let me explain.

At the moment I have 2 models, Buildings and rooms, 1 building can have many rooms.

I want to be able to pass in an array of room ids, and return the sites and only the rooms that are in the array.

Heres what I have at the moment

if($request->input('ids') && !is_null($request->input('ids'))){
    $ids = explode(',',$request->input('ids'));

    //Exploded ids looks like this    "2,4,11,55,56"

    $buildings = Buildings::join('rooms')->whereIn('rooms.id',$ids)->get();
} else {
    $buildings = Buildings::whereHas('rooms')->get();
}

At the moment this will return all buildings that have a room which id is in the ids array and all of its rooms, which ends up returning a building with 200+ rooms. I need it to return the building and ONLY the rooms that have an id in that array.

Is this possible?

I know I can do it the inverse way and get all rooms as the parent then get the buildings, but I need buildings to be the parent as i'm running a foreach like this with the results

foreach($buildings as $key => $building){
    <h1></h1>
    foreach($building->rooms as $k => $room){
      <p></p>
    }
}

Incase thats still confusing, the real world scenario is that i'm generating a PDF of rooms. The rooms can be selected by ticking a checkbox next to the room in a room list. I then need to be able to pass the array of room ids, and get all buildings that contain one of the rooms. Then get all of the rooms for each building where the room id is in the array.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire