I am joining 3 tables, property, facilities, and images. A property has many facilities and has many images.
On my query its looping the same property how many times it has facilities and images and each loop is getting 1 facility and 1 image. What I need to accomplish is it will loop per property and will get all facilities and images a property has.
$properties = DB::table('properties') ->join('facilities', 'properties.id', '=', 'facilities.property_id') ->join('images', 'properties.id', '=', 'images.property_id') ->select('properties.*', 'facilities.feature_name', 'images.img_url') ->paginate(10);
Property Model
public function facilities() { return $this->hasMany(Facility::class); } public function images() { return $this->hasMany(Image::class); }
Facility Model
public function property() { return $this->belongsTo(Property::class); }
Image Model
public function property() { return $this->belongsTo(Property::class); }
Blade
@foreach ($properties as $property) {{ $property->title }}, @endforeach
Advertisement
Answer
you can eager load your relation:
$properties=AppModelsProperty::with(['facilities:property_id,feature_name','images:property_id,img_url'])->paginate(10);
in blade you may do something like:
@foreach ($properties as $property) {{ $property->title }} @foreach ($property->facilities as $facility) {{ $facility->feature_name}} @endforeach // for the images you can do the same @endforeach