我现在不确定在 CakePHP 2.0 中加载模型的最佳方式。
问题1
我有一个模型,其中多个数据库字段与另一个模型相关。
customers
表具有字段 country_origin
、country_residence
和 country_study
,所有这些字段都包含表 countries
中的 ID。
那么在我的客户模型中,我应该如何加载国家/地区模型?
问题2
Controller::loadModel()
是否已被弃用,或者使用它是不好的做法吗?我应该如何在控制器中加载模型?
问题3
何时或为何必须在控制器或模型中使用
App::uses()
?如果您使用 loadModel()
、hasOne
、hasMany
、belongsTo
等常规方法,我不明白模型何时会加载。
这应该很容易理解。如果您正在使用控制器并且需要加载另一个模型,您可以调用:
$this->loadModel('SomeModel');
然后您可以像平常一样调用模型:
$this->SomeModel->read(null, '1');
App::uses
用于延迟加载类。所以你仍然可以使用uses加载模型:
App::uses('MyModel', 'Model');
但是你需要以不同的方式称呼它:
$MyModel = new MyModel();
$MyModel->read(null, '1');
或
MyModel::read(null, '1');
这仅取决于您想在何处以及如何使用它。
首选方式是
$this->load('MyModel');
但是,您也可以使用
public $uses = array('DefaultModel', 'MyModel');
.
.
$this->MyModel->field(...);
Cake 都支持,你可以随意使用任何你喜欢的。
对于问题1
根据您的结构,我认为客户和国家/地区模型之间存在关联,因此我们不需要加载模型。 我们可以为每个 id 创建虚拟关联,例如,
'CountryOrigin' => array(
'className' => 'Country',
'foreignKey' => 'country_origin_id',
'dependent' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
'CountryResidence' => array(
'className' => 'Country',
'foreignKey' => 'country_residence_id',
'dependent' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
通过这样做,我们可以在模型之间创建关联,因此我们不想显式加载模型
当我们没有可以用作的关联时,加载模型是很好的,
加载模型的语法是 对于单一模型负载
$this->loadModel('Country');
如果我们想加载特定动作或条件的模型,这将更有用
如果我们想在整个控制器中使用,我们可以使用 $uses 变量 对于多个模型加载。
public $uses = array('Country','OtherModel');
我们可以访问模型,
$this->Country->find('count');
我最喜欢的方式,也是“更多”未来的证明是以下
$Coordinates = ClassRegistry::init('Coordinates');
$b = $Coordinates->find('all'....);