doume1301 2019-03-05 23:19
浏览 214

如何在模型中使用自定义函数morphMany

(This is about Laravel 5.8)

I know you can create custom functions in your model, but I can't figure out how to make a custom function that uses data from the function morphMany.

What works:
model.php:

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

page.blade.php:

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


This works. But I want to create a function that for example only gives the poster back. But when I place that foreach in a function inside my model. It won't loop trough the images. See the following code:

What doesn't work:
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;
}

The code just returns NULL, what am I missing?

  • 写回答

1条回答 默认 最新

  • dongse5408 2019-03-05 23:28
    关注

    You would like to use the accessor $model->images that returns a collection instead of the query constructor $model->images() that returns a query builder, i.e:

    //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;
    }
    
    评论

报告相同问题?