详细步骤

表设计

字段名字段类型字段说明
idint表id
titlevarchar(36)名称
pidint父级id

模型设计

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<?php

namespace App\Models;

use App\Models\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class User extends Model{
use SoftDeletes;
public $timestamps = true; //软删除
protected $guarded = []; //黑名单
protected $table = 'users'; //表名


public function sonUser() {
//定义模型关联
return $this->hasMany('App\Models\User', 'pid', 'id');
}

public function allSonUser()
{
//递归子用户
return $this->sonUser()
->with('allSonUser')
->select(['id','pid','title']); //此处的字段可根据表设计自行选择
}
}

控制器中使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
namespace App\Http\Controllers;

use App\Models\User;

public function getAllSonId($id){
$son =\App\Models\User::query()->with('allSonUser')->find($id)->allSonUser; //此处find里的id为顶级用户id
$son = json_decode(json_encode($son),true); //转数组
return get_user_id($son);
}

//指定需要的字段并序列化为一维数组
function get_user_id($users)
{
$arr = [];
array_walk_recursive($users,function ($v, $k) use(&$arr) {
if($k == 'id')
$arr[] = $v;
});
return $arr;
}