我在 laravel 中有类别和子类别
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 children()
{
return $this->hasMany('App\Category', 'parent_id');
}
}
我可以添加一个属于已创建类别的新类别。像“测试 -> 测试子类别”,然后假设我将创建属于测试子类别的“测试子子类别”,如下所示:“测试 -> 测试子类别 -> 测试子子类别” 在 View 中,我想打印该类别的父级(如果有)。 我这样做是这样的:
@if($category->parent)
<td>{{ $category->parent->name }} <strong>-></strong> {{ $category->name }}</td>
@else
<td>{{ $category->name }}</td>
@endif
但这仅显示一个父类别(“测试的子类别 -> 测试的子子类别”)。我想向所有家长展示如下所示:“测试->测试子类别->测试子子类别” 我怎样才能做到这一点?
最佳答案
您可以在 Cateory
模型上定义一个模型访问器,用于检索所有父级并将它们放入集合中。因此,在您的 Category
模型中添加以下方法:
public function getParentsAttribute()
{
$parents = collect([]);
$parent = $this->parent;
while(!is_null($parent)) {
$parents->push($parent);
$parent = $parent->parent;
}
return $parents;
}
然后在您的 Blade 模板中,您可以获取类别的所有父级
@if(count($category->parents))
<td>{{ $category->parents->implode('-') }} <strong>-></strong> {{ $category->name }}</td>
@else
<td>{{ $category->name }}</td>
@endif
我认为除了递归检索所有父项和 @Ross Wilson 在评论中建议的包之外,没有其他解决方案不同。请考虑到查询数量将等于父类别的数量。
您可以做的另一件事是将父树设置到categories
表中的数据库中,以节省大量查询。在您的 categories
表中添加一个字符串字段,例如 parents_tree
,并在保存/更新时使用已连接的父级名称设置此值。这有点脏,因为如果 parent 之一更改了名字,您必须相应地更新所有 child 。由您决定要屈服于哪种权衡。
关于php - Laravel 获取类别的所有父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45997680/