我已经在类别类中使用“ parent_id”定义了父级关系,如下所述,我想使用父标题(如mens > show
)打印类别标题。但会抛出
未定义的属性: 照亮\ 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;
}
}
CategoryController
.......
namespace App\Http\Controllers;
use App\Category;
class CategoryController extends Controller
{
public function index(){
$categories = Category::get();
foreach($categories as $category){
echo $category->withParentTitle();
}
}
}
答案 0 :(得分:1)
根据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;
答案 1 :(得分:0)
您必须在没有()
的情况下拨打电话:
public function withParentTitle(): string
{
if($this->parent()){
return $this->parent->title.' > '. $this->title;
}
return $this->title;
}
因为如果您使用()
,您将在关系中调用为查询生成器,并且可以使用其他闭包:
$this->parent()->where('title', 'foo')->first();
答案 2 :(得分:0)
public function withParentTitle(): string
{
// Your $this->parent() would always be true,
// use $this->parent()->exists() instead
if($this->parent()->exists()){
// $this->parent() refers to the relationship,
// you can't get title out of the relationship object,
// unless you retrieve it using $this->parent
return $this->parent->title.' > '. $this->title;
}
return $this->title;
}