[英]Laravel: Joining tables in Laravel and loop on the other tables
我要加入 3 张桌子、财产、设施和图像。 一个属性有很多设施,有很多图像。
在我的查询中,它循环相同的属性多少次它有设施和图像,每个循环得到 1 个设施和 1 个图像。 我需要完成的是它将循环每个属性,并获取属性的所有设施和图像。
$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);
属性 Model
public function facilities() {
return $this->hasMany(Facility::class);
}
public function images() {
return $this->hasMany(Image::class);
}
设施 Model
public function property() {
return $this->belongsTo(Property::class);
}
图片 Model
public function property() {
return $this->belongsTo(Property::class);
}
刀
@foreach ($properties as $property)
{{ $property->title }},
@endforeach
你可以急切地加载你的关系:
$properties=\App\Models\Property::with(['facilities:property_id,feature_name','images:property_id,img_url'])->paginate(10);
在刀片中,您可以执行以下操作:
@foreach ($properties as $property)
{{ $property->title }}
@foreach ($property->facilities as $facility)
{{ $facility->feature_name}}
@endforeach
// for the images you can do the same
@endforeach
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.