增加TP,Think php中model的左连接 功能。table功能,多个where条件增强增强

浏览:2917 发布日期:2013/12/14 分类:技术分享
//左连接是开发中经常用的功能。但是TP封装的不彻底。还不够easy和傻瓜化。想要用,必须会自己写左连接的sql语句。我们把他增强后,可以让一个不会多表连接的同学立即会使用多表连接。而不必会多表连接的SQL语句,这就是此函数的意义.

// 任何多个where条件增强

//重建表信息 table/**
 * 通用的Model类。可以进行基本的增删查改动作。
 */
class  CommonModel extends Model
{
    // 模型名称
    protected $name='';
    
    public function __construct($name='',$tablePrefix='',$connection='')
    {
        parent::__construct($name,$tablePrefix,$connection);
    }

   /**
     * 左连接
     * @param string $link_table_name 连接的表名
     * @param string $main_field_name 要连接的主表名中字段名
     * @param string $link_field_name  为要建立连接中表的字段名
     * @return 返回自己对象.
     */
    public function joinOn($link_table_name,$main_field_name,$link_field_name='')
    {
        if($link_field_name=='')
        {
            $link_field_name=$main_field_name;
        }
        if(!strpos($link_field_name, '.')) //自带表名了 在自连接时,必须要自带表名才可以确定是要连接的哪个字段
        {
            $link_field_name="$link_table_name.$link_field_name";
        }
        return $this->join(" $link_table_name  on {$this->trueTableName}.$main_field_name=$link_field_name");
        
    }

    /**
     * 原php中table方法有问题,在重新设置表时没有重建整个表信息,此方法弥补此错误。
     * @param string $tableName
     * @return Model对象
     */
    public function table($tableName)
    {
        $this->trueTableName=$tableName;
        $this->flush();
        return $this;
    }

  /**
     * 指定查询条件 支持任意多个where 连贯操作
     * @access public
     * @param mixed $where 条件表达式
     * @param mixed $parse 预处理参数
     * @return Model
     */
    public function where ( $where , $parse = null )
    {
        if (! is_null($parse) && is_string($where))
        {
            if (! is_array($parse))
            {
                $parse = func_get_args();
                array_shift($parse);
            }
            $parse = array_map(array($this->db,'escapeString'), $parse);
            $where = vsprintf($where, $parse);
        } elseif (is_object($where))
        {
            $where = get_object_vars($where);
        }
        if (is_string($where) && '' != $where)
        {
            $map = array();
            $oldWhere=$this->options['where']['_string'] ;
            if($oldWhere)
            {
                $where=$oldWhere.' and '.$where; //此处代码增强,让字符串条件可以多个
            }
            $map['_string'] = $where;
            $where = $map;
        }
        
        if (isset($this->options['where']))
        {
            $this->options['where'] = array_merge($this->options['where'], $where);
        } else
        {
            $this->options['where'] = $where;
        }   
        return $this;
    }
    
}
//请大家拍砖。有需要的可以直接拿过去用。可以化复杂为简单。
最佳答案
评论( 相关
后面还有条评论,点击查看>>