最近尝试移植一个小项目到php,选择了tp框架,遇到一个视图模型方面的问题,虽然解决了,但是却有些想法,
先上相关代码:
//------------------------------------------
/*ResIndustryModel.class.php*/
<?php
namespace Home\Model;
use Think\Model;
class ResIndustryModel extends Model {
protected $connection = 'DB_EDJRES';
}
//------------------------------------------
//------------------------------------------
/* IndustrySelItemViewModel.class.php*/
<?php
namespace Home\Model;
use Think\Model\ViewModel;
class IndustrySelItemViewModel extends ViewModel{
protected $connection = 'DB_EDJRES';
public $viewFields = array(
// 先看后面的前提
// 1.失败,namespace不对将会导致 class_exists为false,然后采用M方法实例化ResIndustryModel类,最终按默认配置读取默认数据库,失败
//'ResIndustry' => array('industry_id'=>'value', 'industry_name'=>'text');
// 2.失败,模型是可以找到了,问题是Think\Model\ViewModel 类中代码=》$tableName .= !empty($view['_as'])?' '.$view['_as']:' '.$key;会出问题。
//'\Home\Model\ResIndustry' => array('industry_id'=>'value', 'industry_name'=>'text');
// 3.成功,使用了as,避免了2的错误
//'\Home\Model\ResIndustry' => array('_as'=>'a', 'industry_id'=>'value', 'industry_name'=>'text');
// 4.成功,指定了table name,将走另外一个逻辑
'ResIndustry(或任意合法as值)' => array('_table'=>'edj_res_industry','industry_id'=>'value', 'industry_name'=>'text');
// ..更多失败或成功的用法不列出来了,大同小异
);
}
//------------------------------------------
//------------------------------------------
// 控制器中实例化
$data = (new IndustrySelItemViewModel())->select();
//------------------------------------------
首先说明一下该问题的前提是涉及多个数据库,并且默认配置为另外一个数据库,根据tp手册的阅读我选了一个我认为比较合适并自己比较喜欢的方法(覆盖$connection)来做,
对于php,我是一个新手,接触php和tp不到一个礼拜,我也不能完全确定是否我的用法有问题或者说有更好的方法来实现同样的功能,如果有请指正。
根据我的注释,可以看到我最终找到了正确执行的方法,过程很艰辛,跟踪调试,查看源代码。。。
关键是下次不一定记得住。
希望第2种方法能在后续版本中得到支持,这个不能说一定是bug,但是感觉。。。
最佳答案