<?php

//合伙人用户
namespace app\shared\model;

use think\Model as ThinkModel;
use think\facade\Db;
class PartnerUser extends ThinkModel
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'shared_partner_user';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    //孩子
    static public function childAll($user_id=1,$level=1,$field='',$page=0,$is_all=0){
    	if($field){
    		$field=explode(',', $field);
    	}else{
    		$field=['id','parent_id'];
    	}
    	foreach ($field as &$value) {
    		$value='T2.'.$value;
    	}
    	$field=implode(',', $field);
    	if($is_all==1){
    		$search_level="T1.clevel <= {$level}";
    	}else{
    		$search_level="T1.clevel = {$level}";
    	}
    	if($page>0){
    		$page-=1;
    	}
    	$limit=10;
    	$page=$page*$limit;
    	$table=self::getTable();
		$sql3="
		SELECT
			{$field},
			T1.clevel 
		FROM
			(
			SELECT
				@r AS _pid,
				(
				SELECT
					@r := group_concat( id ) 
				FROM
					`{$table}` 
				WHERE
				FIND_IN_SET( parent_id, _pid )) AS cid,
				@l := @l + 1 AS clevel 
			FROM
				( SELECT @r := {$user_id} ) vars,-- 查询id为4的所有子节点
				( SELECT @l := 0 ) clevel,
				{$table} h 
			WHERE
				@r IS NOT NULL 
			) T1
			INNER JOIN {$table} T2 ON FIND_IN_SET( T2.parent_id, T1._pid ) 
		WHERE
			{$search_level}
		ORDER BY
			id ASC
		LIMIT {$page},{$limit};	
		";
		return Db::query($sql3);
    }
}