我有这张category表:
| ID | 姓名 | 父 ID |
|---|---|---|
| 1 | 编程 | 0 |
| 2 | 历史 | 0 |
| 3 | PHP | 1 |
| 4 | JavaScript | 1 |
| 6 | 世界历史 | 2 |
| 7 | jQuery | 4 |
| 8 | 阿贾克斯 | 4 |
| 9 | 欧洲 | 6 |
| 10 | 美国人 | 6 |
| 16 | 阿贾克斯嵌套 | 8 |
这是我在控制器中获取类别的方法:
$categories = Category::where('parent_id', '=', 0)->with('childs')->get();
Run Code Online (Sandbox Code Playgroud)
及型号类别:
class Category extends Model
{
use HasFactory;
protected $fillable = ['name'];
public function user()
{
return $this->belongsTo(User::class);
}
public function posts()
{
return $this->hasMany(Post::class)->orderBy('created_at', 'DESC');
}
public function childs()
{
return $this->hasMany(Category::class, 'parent_id', …Run Code Online (Sandbox Code Playgroud)