ThinkPHP 关联模型中查询某条记录的父级(非查询子级)

数据表

id      cat_name      cat_pid     

76     手机、数码     0      

84     手机配件        76

86     蓝牙耳机        84

从属关系 : 蓝牙耳机  =>(上一级)  手机配件   =>(上一级)  手机、数码(顶级了)  

关联模型

namespace AdminModel;
use ThinkModelRelationModel;
class CategoryModel extends RelationModel
{
	protected $_link = array(
          'Category' => array(     //表名
              'mapping_type'=>self::BELONGS_TO,   //关键.这个是查询父级的  而HAS_MANY则是查询子级的
              'mapping_name'=>'_parent', //自定义
              'mapping_order'=>'cat_sort',
              'parent_key'=>'cat_pid',//关键.父级关联的字段名 
          ),
	);
}


控制器中的代码:
public function search()
{
$category = D('Category'); //要用D方法.才能使用关联模型
  $id = 86;   //这时候86这个id是数据表中最底层的一级.
  $this->id = $category->where('id='.$id)->order('cat_sort')->relation(true)->select();   //这时候查询出来的是86的上一级.即id=84,手机配件   
  $lastPid = $category->relationGet(true);   //如果希望在完成的查询基础上,在进行关联查询.则使用relationGet()方法
  //dump($lastPid);
  //这时候的$lastPid就是最顶层的数据(id=76,手机,数码).(前提是数据表为三层结构.如果是两层结构,则$this->id就已经到顶层了,就不需要在使用relationGET()方法)
//假如再来一次,就能查询到更高的父级,前提是数据表为四层结构,以此类推
  //$lastLastPid = $category->relationGet(true);
}

原文地址:https://www.cnblogs.com/meibao/p/4645536.html