Laravel 5从刀片中收集属性

时间:2015-12-02 16:06:34

标签: php laravel collections laravel-5 blade

我需要从属性模型中获取所有图像。 但我得到的只是一个带图像的集合,但我不知道如何访问它们。

以下是一些代码:

PropertyController

public function show($id)
{
    $property = Property::findOrFail($id);
    $main_image = $property->images()->mainImage()->get();
    $images = $property->images()->get();

    return view('property.single',compact('property', 'images', 'main_image'));
}

我在Property和image之间建立了关系:

物业模型:

public function images()
{
    return $this->hasMany('App\Image');
}

图片模型:

public function property()
{
    return $this->belongsTo('App\Property');
}

public function scopeMainImage($query)
{
    $query->where('main_image', '=', 1);
}

我认为{{$ main_image-> file_name}}完成了这项工作,但print_r返回了一些集合

[...]

[attributes:protected] => Array
                    (
                        [id] => 20
                        [property_id] => 25
                        [user_id] => 2
                        [file_name] => main_image.jpg
                        [file_type] => jpg
                        [file_url] => img/properties/25/main_image.jpg
                        [main_image] => 1
                        [created_at] => 2015-12-02 15:31:03
                        [updated_at] => 2015-12-02 15:31:03
                    )

[...]

那么我该怎么做才能改变它来访问这个集合呢?

谢谢!

1 个答案:

答案 0 :(得分:3)

当您在Eloquent查询构建器上调用 get()时,即使返回了一条记录,您也将始终获得一个集合。首先调用 first(),然后您将获得集合中的第一个(也是唯一的 - 在您的情况下)对象:

$main_image = $property->images()->mainImage()->first();