php - laravel - 使用自定义模型函数获取父类别图块
问题描述
我已经使用下面提到的“parent_id”在类别类中定义了父关系,我想打印带有父标题的类别标题,例如mens > show
。但它抛出
未定义属性:Illuminate\Database\Eloquent\Relations\BelongsTo::$title
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
//
protected $table = 'categories';
public function parent()
{
return $this->belongsTo('App\Category', 'parent_id');
}
public function withParentTitle(): string
{
if($this->parent()){
return $this->parent()->title.' > '. $this->title;
}
return $this->title;
}
}
类别控制器
......
namespace App\Http\Controllers;
use App\Category;
class CategoryController extends Controller
{
public function index(){
$categories = Category::get();
foreach($categories as $category){
echo $category->withParentTitle();
}
}
}
解决方案
根据 laravel 文档https://laravel.com/docs/5.8/eloquent-mutators
你可以accessors
通过这种方式使用
public function getParentTitleAttribute(){
return $this->parent ? $this->parent->title . '>' . $this->title : $this->title;
}
然后打电话$category->parent_title;
推荐阅读
- regex - 包括使用“grok”模式(或正则表达式)的 Telegraf 插件 inputs.logparser 的额外测量
- python-3.x - RuntimeError:此包仅支持 Linux、MacOSX 或 Windows 平台错误,ChromeDriver 和 Chrome 通过 Selenium 和 Python
- mysql - 如何在 MySQL 中获取一个特定 JSON 键的值
- react-native - 如何使语音识别器的哔声静音?
- java - 在 Dropwiard 应用程序中访问 guice 容器
- python - 在 df 端添加单个字段
- excel - 循环复制一个目标单元格中的单元格,而不是移动到下一个目标单元格
- r - 生成网址?如何从向量变量构建 URL?
- scala - Scala单例对象中值的Java序列化
- spring - ADFS 中是否有任何用于检查令牌的端点?