【问题标题】:Laravel 5 get property from collection in bladeLaravel 5 从刀片中的集合中获取属性
【发布时间】:2016-03-06 23:13:35
【问题描述】:

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

这是一些代码:

属性控制器

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

我设置了属性和图像之间的关系:

属性模型:

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
                    )

[...]

那么我可以做些什么来改变它来访问这个集合?

谢谢!

【问题讨论】:

    标签: php laravel collections laravel-5 blade


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-19
      • 2014-01-22
      • 2013-08-08
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 2021-07-16
      • 2019-12-26
      相关资源
      最近更新 更多