【发布时间】:2021-06-05 03:35:07
【问题描述】:
有一个 MySQL "Categories" 表。
Category 模型具有如下所示的“hasMany”关系。
public function children(){
return $this->hasMany(self::class, 'parent_id');
}
在类别编辑页面上,为了将父类别分配给当前类别(为此我需要填写其 parent_id 字段),我必须生成一个 Select 标记,该标记将包含类别表中的所有行,当前类别及其所有子类别除外。
category_id | parent_id
------------------------
1 | NULL
2 | 1
3 | 2
4 | 3
5 | NULL
6 | 5
For example,
for category_id 1, should be selected lines with category_id [5, 6]
for category_id 2, should be selected lines with category_id [1, 5, 6]
for category_id 3, should be selected lines with category_id [1, 2, 5, 6]
for category_id 4, should be selected lines with category_id [1, 2, 3, 5, 6]
for category_id 5, should be selected lines with category_id [1, 2, 3, 4]
for category_id 6, should be selected lines with category_id [1, 2, 3, 4, 5]
如果一个category有parent_id为NULL,则表示它没有父category。
【问题讨论】:
-
parent_id 是干什么用的?您给出的示例没有 parent_id 并且 parent_id 值不唯一?
-
"parent_id" 是包含父类别 ID 的字段。需要此字段才能知道该类别属于哪个父类别。
标签: mysql laravel laravel-query-builder