Laravel:连接 Laravel 中的表并在其他表上循环

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);

属性 型号

public function facilities() {
    return $this->hasMany(Facility::class);
}

public function images() {
    return $this->hasMany(Image::class);
}

设施模型

public function property() {
    return $this->belongsTo(Property::class);
}

图片模型

public function property() {
    return $this->belongsTo(Property::class);
}

Blade

    @foreach ($properties as $property)
        {{ $property->title }}, 
    @endforeach

你可以eager load你的关系:

    $properties=\App\Models\Property::with(['facilities:property_id,feature_name','images:property_id,img_url'])->paginate(10);

在 blade 中你可以做类似的事情:

@foreach ($properties as $property)
        {{ $property->title }}
          @foreach ($property->facilities as $facility)
               {{ $facility->feature_name}}
          @endforeach
        // for the images you can do the same 
          
    @endforeach