如何仅返回一对多关系的子模型-Laravel

时间:2019-01-24 13:01:53

标签: laravel eloquent

我希望可以在这里得到一些帮助。

这是我的模型结构:

Property 1
--Image 1
--Image 2
Property 2
--Image 3
--Image 4

我要尝试的是检索所有图像模型。

这是我尝试过的:

$properties = Auth::user()
    ->landlord_profile_auto
    ->properties()
    ->with('images')
    ->get();

dd($properties->images);

Property [images] does not exist on this collection instance.

非常感谢

编辑:

这是属性的转储:

>>> Property::whereHas('images')->with('images')->first()
=> App\Models\Property {#3064
 id: 3,
 created_at: "2019-01-23 17:31:34",
 updated_at: "2019-01-23 20:22:45",
 address_line_1: "ABC",
 address_line_2: "ABC",
 unit: "calculateStorageUsage",
 city: "ABC",
 postal_code: "calculateStorageUsage",
 url_slug: null,
 is_draft: 0,
 is_refurb: 0,
 purchased_date: "2019-01-23",
 bedrooms: 3,
 max_tenants: null,
 rent_amount: "589595.00",
 currency_id: 252,
 country_id: 491,
 rent_frequency_id: 7,
 property_type_id: null,
 featured_image_id: 4,
 landlord_profile_id: 6,
 images: Illuminate\Database\Eloquent\Collection {#3059
   all: [
     App\Models\Image {#3078
       id: 4,
       created_at: "2019-01-23 20:22:42",
       updated_at: "2019-01-23 20:22:42",
       name: null,
       caption: null,
       path: "property_images/Ba1XYIB394xLsH4365391beAZ.jpg",
       size_kb: 849.85,
       imageable_type: "App\Models\Property",
       imageable_id: 3,
     },
     App\Models\Image {#3077
       id: 5,
       created_at: "2019-01-23 20:22:45",
       updated_at: "2019-01-23 20:22:45",
       name: null,
       caption: null,
       path: "property_images/An3bgmKJzMcPuZyYizp9Lm6dj.jpg",
       size_kb: 849.85,
       imageable_type: "App\Models\Property",
       imageable_id: 3,
     },
   ],
 },
}

属性与图像具有一对多的关系。图片是一个多态表。

1 个答案:

答案 0 :(得分:0)

尝试一下:

@foreach($properties->images as $image)
{
 // here you can acess each image
}
@endforeach