问题出现的原因是因为视图模型中并未使用Connection指定的数据库! 处理方式:自定义一个视图继承自\Think\Model\ViewModel,并重写getTableName方法,调用M函数的时候传递connection 1. [代码] [PHP]代码
处理方式: 自定义一个视图继承自\Think\Model\ViewModel,并重写getTableName方法,调用M函数的时候传递connection
1. [代码][PHP]代码
<?php
namespace Common\Model;
/**
* ViewModel处理
* @author hxtgirq
* @date 2016-07-15
*/
class ViewModel extends \Think\Model\ViewModel {
public function getTableName() {
if(empty($this->trueTableName)) {
$tableName = '';
foreach ($this->viewFields as $key=>$view){
// 获取数据表名称
if(isset($view['_table'])) { // 2011/10/17 添加实际表名定义支持 可以实现同一个表的视图
$tableName .= $view['_table'];
$prefix = $this->tablePrefix;
$tableName = preg_replace_callback("/__([A-Z_-]+)__/sU", function($match) use($prefix){ return $prefix.strtolower($match[1]);}, $tableName);
}else{
$class = $key.'Model';
$Model = class_exists($class)?new $class():M($key,'',$this->connection);
$tableName .= $Model->getTableName();
}
// 表别名定义
$tableName .= !empty($view['_as'])?' '.$view['_as']:' '.$key;
// 支持ON 条件定义
$tableName .= !empty($view['_on'])?' ON '.$view['_on']:'';
// 指定JOIN类型 例如 RIGHT INNER LEFT 下一个表有效
$type = !empty($view['_type'])?$view['_type']:'';
$tableName .= ' '.strtoupper($type).' JOIN ';
$len = strlen($type.'_JOIN ');
}
$tableName = substr($tableName,0,-$len);
$this->trueTableName = $tableName;
}
return $this->trueTableName;
}
}
