larvel刀片模板和元素模型-如何获得许多关系中的第一个元素

时间:2018-12-18 17:09:07

标签: laravel laravel-blade

我有以下雄辩的模型(已删除代码以简化此问题)。我正在尝试获取第一张图片

class Design extends Model
{
    use SoftDeletes;

    protected $guarded = ['id','tags','keywords'];

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

class DesignImage extends Model
{
    use SoftDeletes;

    public function design()
    {
        return $this->belongsTo(Design::class);
    }
}

然后我将以下代码传递给刀片模板

$data['designs'] = Design::where('quantity','>',0)->get();
return view('mailings.form',$data);

模板(效果很好;我得到了所有图像的名称

@foreach($design->images as $image)
    {{ $image->name }}
@endforeach

但是,如果我尝试

{{ $design->images->first()->name }}

我试图获取非对象的属性“名称”

如果我尝试

{{ $design->images[0]->name }}

我得到未定义的偏移量:0

但是我愿意

@json ($design->images->first())

我得到(有效)

{“ id”:1,“ name”:“ Image 1 Design 1”,“ thumb”:“ images / main_thumb.jpg”,“ image”:“ images / main_large.jpg”,“ design_id”:1 ,“ created_at”:“ 2018-12-11 20:10:03”,“ updated_at”:“ 2018-12-11 20:10:03”,“ deleted_at”:null}

如何获取刀片模板中的第一张图像?为什么我得到这个奇怪的输出?

1 个答案:

答案 0 :(得分:1)

发生错误是因为最新的$design没有image。试试这个代码

@foreach($designs as $design)
    // your code
    @php
        $firstImage = $design->images()->first();
    @endphp
    {{ !empty($firstImage->name) ? $firstImage->name : ''}}
    // other part ofcode
@endforeach

您还可以在控制器中使用此代码

$data['designs'] = Design::where('quantity','>',0)->with('images')->get();
return view('mailings.form',$data); 

可见

@foreach($designs as $design)
    // your code
    @php
        $firstImage = $design->images->first();
    @endphp
    {{ !empty($firstImage->name) ? $firstImage->name : ''}}
    // other part ofcode
@endforeach