php - 如何在模型中将 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,我错过了什么?
解决方案
您想使用$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;
}
推荐阅读
- postgresql - 使用 Spring Batch 从具有数据转换的表中卸载
- mysql - CloudFunction 访问托管在计算机引擎虚拟机上的 MySQL
- azure - 二头肌删除“现有”密钥保管库资源
- firebase - Firestore 安全规则,正则表达式,如何避免特殊字符
- javascript - 访问数组中获取的数据?
- elasticsearch - 我收到 Logstash 错误:IllegalStateException
- python - 从具有相同值的 csv 文件创建字典
- c++ - NodeJS插件构建错误C3861:'_alloca':找不到标识符
- list - google sheet - 根据列和行中的内容列出(或编号)
- flutter - 以下包不支持空安全