Laravel刀片得到了遥远的关系数据

时间:2017-03-24 16:55:26

标签: php laravel

我有一个有很多图像的相册模型,我可以在控制器中获取它(并将其传递给视图),如下所示:

$albums = Album::with('images')->get();
return view('welcome', ['albums' => $albums]);

对数据执行var_dump似乎按预期工作:

images: 
(object) Illuminate\Database\EloquentCollection [Object ID: 377][Number of Properties: 1]
items:protected: 
(array) [Number of elements: 5]
0: 
(object) AppImage [Object ID: 382][Number of Properties: 24]
table:protected: (string) image
connection:protected: (null) NULL
primaryKey:protected: (string) id
keyType:protected: (string) int
incrementing: (boolean) true 
with:protected: 
(array) [Number of elements: 0]
perPage:protected: (integer) 15 
exists: (boolean) true 
wasRecentlyCreated: (boolean) false 
attributes:protected: 
(array) [Number of elements: 6]
id: (integer) 1 
filename: (string) vAIsX53hlkRUSkmohe0SyeEhEzkDTQnsQxrL3DKt.png
path: (string) images/20170322000000
album_id: (integer) 1 
created_at: (string) 2017-03-22 16:02:55
updated_at: (string) 2017-03-22 16:02:55
original:protected: 
(array) [Number of elements: 6]
id: (integer) 1 
filename: (string) vAIsX53hlkRUSkmohe0SyeEhEzkDTQnsQxrL3DKt.png
path: (string) images/20170322000000
album_id: (integer) 1 
created_at: (string) 2017-03-22 16:02:55
updated_at: (string) 2017-03-22 16:02:55

我循环播放专辑并打印出标题并且工作正常,但是当试图访问专辑对象中的图像对象时,我没有得到任何输出:

                @foreach ($albums as $album)

                    {{ $album->name }} <br>
                    @foreach ($album->images() as $image)
                        {{ $image->filename }}
                    @endforeach

                @endforeach

{{ $album->name }}按预期工作但我没有输出{{ $image->filename }}我是否尝试错误地访问图片文件名?

1 个答案:

答案 0 :(得分:3)

当您将关系作为方法调用时,它将返回查询构建器实例。您需要将其更改为属性调用以获取图像集合。

所以改变

@foreach ($album->images() as $image)

@foreach ($album->images as $image)