首页 > 解决方案 > 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();
        }
    }
}

标签: phplaravel

解决方案


根据 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;


推荐阅读