我在“类别”表中有下表。
| id | 姓名 | parent_id |
|---|---|---|
| 1 | 学生 | 空 |
| 2 | 老师 | 空 |
| 3 | 数学学生 | 1 |
| 4 | 科学学生 | 1 |
我在“发布”表中有下表。
| id | 姓名 | category_id |
|---|---|---|
| 1 | 阿杰 | 3 |
| 2 | 莫汉 | 3 |
模型中的 Post.php 文件
public function category(){
return $this->belongsTo(Category::class, 'category_id', 'id');
}
如果我放置以下代码,我将获得第三个 id 的名称,即 math_student。
$post->category->name
但我想获取该类别的parent_id的名称,即-“学生”
我尝试了以下代码,但错误。
$post->category->parent_id->name
请给我建议解决方案
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
在类别模型中,添加父关系:
public function parent(){ return $this->belongsTo(Category::class, 'parent_id', 'id')->withDefault(); }然后,就可以获取父名称
您需要使用
parent_id建立关系,以在其内部查找Category的模型实例。在 Category.php 模型中:
public function parent(){ return $this->belongsTo(Category::class, 'parent_id', 'id'); }之后,您将能够: