首页 > 解决方案 > 如何在模型中将 morphMany 与自定义函数一起使用

问题描述

(这是关于 Laravel 5.8)

我知道你可以在你的模型中创建自定义函数,但我不知道如何制作一个使用来自函数 morphMany 的数据的自定义函数。

什么有效:
model.php:

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

page.blade.php:

@foreach($model->images() as $image)
    {{ $image->url }}
@endforeach


这行得通。但我想创建一个功能,例如只返回海报。但是当我把那个 foreach 放在我的模型中的一个函数中时。它不会循环遍历图像。请参阅以下代码:

什么不起作用:
model.php:

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

public function poster()
{
    $images = $this->morphMany('App\Image', 'owner');

    foreach($images as $image)
    {
        /* THIS CODE WILL NEVER RUN SOMEHOW */
        if ($image->type == "poster")
        {
            return $image;
        }
    }
    return NULL;
}

代码只返回NULL,我错过了什么?

标签: phplaravellaravel-5eloquent

解决方案


您想使用$model->images返回集合的访问器而不是$model->images()返回查询构建器的查询构造函数,即:

//page.blade.php
@foreach($model->images as $image)
    {{ $image->url }}
@endforeach

// in Model    
public function poster()
{ 
    foreach($this->images as $image)
    {
        if ($image->type == "poster")
        {
            return $image;
        }
    }
    return NULL;
}

推荐阅读