<?php
namespace Admin\RelationModel;
use Think\Model\RelationModel;
class DatadictRelationModel extends RelationModel{

	protected $tableName = 'datadict';

	/* 自动验证规则 */
	protected $_validate = array(
		array('id', 'number', '非法提交', self::MUST_VALIDATE, 'regex', self::MODEL_UPDATE),
		array('pid', 'number', '父级选择错误', self::MUST_VALIDATE , 'regex', self::MODEL_BOTH),
		array('category_id', 'number', '类型选择错误', self::MUST_VALIDATE , 'regex', self::MODEL_BOTH),
		array('text', '1,20', '标题字数介于0-40字', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
		array('value', '1,60', '值字数介于0-20字', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
		array('value', 'require', '值不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
		array('value', 'isunique', '值不能重复', self::MUST_VALIDATE, 'callback', self::MODEL_BOTH),
		array('sort', 'number', '排序必须为数字', self::VALUE_VALIDATE , 'regex', self::MODEL_BOTH),
		array('status', array('0','1'), '状态错误', self::VALUE_VALIDATE , 'in', self::MODEL_BOTH),
	);

	// 自动完成规则
	protected $_auto = array (
		array('create_time','datetime',1,'function'), 
		array('update_time','datetime',3,'function'),
		array('system',0,3),
	);

	protected function isunique(){
		$where = array();
		$where['category_id'] = array('EQ',I('category_id','','intval'));
		if (I('id','','intval')) {
			$where['id'] = array('NEQ',I('id','','intval'));
		}
		$values = M('Datadict') -> where($where) -> getField('value',true);
		if (in_array(I('value'), $values)) {
			return false;
		}
		return true;
	}
}