用 phalcon 数据模型 前缀
可能是经验不足吧,实际上只需要在模型的 initialize
方法上设置上 表名就可以了。
abstract class ModelBase extends Model
{
protected $prefix = 'x_';
protected $tableName = '';
public function initialize()
{
if (empty($this -> prefix)) {
return;
}
$this -> setSource("{$this -> prefix}{$this->tableName}");
}
}
只需要简单的设置一下上面的内容就可以了,设置完成获取的时候自然就能获取正确的表名了。
关于命名空间需要看一下路由相关的配置了。
更新时间 2019年5月31日 11:02:36
下面是旧的内容
在我使用phalcon 的数据库模型的时候,发现没有前缀的设置项,但是现在的几乎所有的数据库都会设置一个前缀吧。
我的小小坑
也是有前缀的。
由于没有设置前缀项,于是又到了去网上遨游的时候了。
找了且仅找了一个,关于说明 phalcon 关于数据库前缀的。
我嫌麻烦所以使用第一个吧。
但是我用的是带命名空间的呀,各种水土不服。
用第一个不行哇。
思想飘到田边
又回来。嘿嘿……,想到了办法。
重点来了:
我干吗获取类名来设置表名呢,万一表名我是自定义的呢,类名也是不对的呀。
于是,我调用 父级的 getSource()
形成下面的这个样子,
先添加一个 父级模型
namespace App\Model;
use \Phalcon\MVC\Model;
class CommonModel extends Model
{
protected $prefix = 'jief_';
public function getSource()()
{
$table = parent::getSource();
return ($this -> prefix . $table);
}
}
又想到了个办法
这样更符合我的心意,用 ThinkPHP
和 Laravel
习惯了。
namespace App\Model;
use \Phalcon\MVC\Model;
class CommonModel extends Model
{
protected $prefix = 'jief_';
protected $tableName = '';
public function initialize()
{
$this -> setSource($this -> prefix . $this -> tableName);
}
}
这样的话 继承上面的模型,并设置 表名属性,就可以获取正确的表名了。
感觉还缺点啥。
又改了下
namespace App\Model;
use \Phalcon\MVC\Model;
class CommonModel extends Model
{
protected $prefix = 'jief_';
protected $tableName = '';
public function initialize()
{
$this -> setSource($this -> prefix . $this -> tableName);
}
public function getSource()
{
if(empty($this -> tablaName)){
return ($this -> prefix).(parent::getSource());
}
}
}
上面的感觉比较满意了。先用几天。
出问题了:
- 获取模型对应的表名 回去不到
- 初始化判断表名是不是设置了
解决问题后的代码:
namespace App\Model;
use \Phalcon\MVC\Model;
class CommonModel extends Model
{
protected $prefix = 'jief_';
protected $tableName = '';
public function initialize()
{
if(!empty($this -> tableName)) // 判断表名有没有设置
$this -> setSource($this -> prefix . $this -> tableName);
}
public function getSource()
{
if(empty($this -> tablaName)){
return ($this -> prefix).(parent::getSource());
}
return parent::getSource();
}
}
评论已关闭