How to use models without database on CakePHP and have associations?
I've got the field country_id
in one of my models and instead of creating a countries
table which contains a list of countries that doesn't change, what's the best approach to this?
I'm thinking about using a model without a database table but I don开发者_JAVA百科't know how to implement this.
Please help. Thanks in advance!
you can totaly use the no table syntax:
class ModelWithoutTable extends AppModel
{
var $useTable = false;
}
to have this Country Model tableless, but you need to mock a data source (i.e. XML,YAML,PHP Array and etc) for the countries data.
Hope this helps.
I would suggest using ArraySource
from the community-maintained CakePHP Datasources plugin:
- CakePHP 1.3.x - see
master
branch - CakePHP 2.x - see
2.0
branch
Download the entire plugin and extract the contents to app/plugins/datasources
.
Define a connection to the datasource in app/config/database.php
:
public $array = array('datasource' => 'Datasources.array');
This should allow you to emulate a table by defining records in your model:
class Country extends AppModel {
public $useDbConfig = 'array';
public $records = array(
array('id' => 1, 'name' => 'Test record')
);
}
As alternative, if there's no other data attached to the country besides, basically, an id of what country it is, you can probably keep it within the same model without association. Something along the lines of:
class MyModel extends AppModel {
public static $countries = array(
'Africa', 'America', ..., 'Zululand'
);
public $validate = array(
'country' => array(
'rule' => array('inList', self::$countries),
...
)
)
}
精彩评论