Correct CakePHP model relations - cakephp-2.0

I have the following logical/model setup in CakePHP and can't understand what is the correct relationship that should be in place for this setup (nor really get my head around the relations in general):
[Model] Quiz
[Model] Question
[Model] QuizQuestion
[Model] Patient
[Model] PatientQuiz
I think it's fairly self explanatory:
A patient can be associated with several quizzes
A question can be associated with one quiz (currently)
Each quiz has many questions
Thanks!

The model associations are straightforward.
class Quiz extends AppModel
{
public $hasMany = array('Question');
public $belongsTo = array('Patient');
}
class Question extends AppModel
{
public $belongsTo = array('Quiz');
}
class Patient extends AppModel
{
public $hasMany = array('Quiz');
}
You don't need the QuizQuestion or PatientQuiz models.

Related

cakephp Appmodel access child tables

There are a relationship between Appmodel and child model. Is that mean it can access every database table ? However, i cannot access the child database. Is there any difference with the sytax?
App::uses('AppModel', 'Model');
class CompanyAppModel extends AppModel{
$this->Brand; it works
$this->BrandLangauge; it does not work
}
class BrandLanguage extends CompanyAppModel {
}
class Brand extends CompanyAppModel {
}
I'm not clear the question. But, you can use ClassRegistry::init needing to load a model that’s not associated with the current model.
$anotherModel = ClassRegistry::init('AnotherModel');

CakePHP 2.x: call virtual fields over associated model

i have the Model ExternalShare, which hasOne SfileVersion. And a third Model Sfile, which hasMany SfileVersion.
In SfileVersion i have in $virtualFields the following code:
class SfileVersion extends AppModel {
public $virtualFields = array(
'active' => 'SfileVersion.is_active',
'externalShare' => 'ExternalShare.id'
);
[...]
}
AppModel looks like the following code, so, Containable is available everywhere:
class AppModel extends Model {
public $recursive = -1;
public $actsAs = array('Containable');
}
Now i try to call the find('all') method in SfileController, to get data from Sfile and SfileVersion:
class SfilesController extends AppController {
public function index() {
$this->Sfile->recursive = 0;
$this->Sfile->contain('SfileVersion');
$allSfiles = $this->Sfile->find('all');
}
[...]
}
Now i get the follwing error:
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ExternalShare.id' in 'field list'
In the CookBook (http://book.cakephp.org/2.0/en/models/virtual-fields.html#limitations-of-virtualfields), here is
A common workaround for this implementation issue is to copy
virtualFields from one model to another at runtime when you need to
access them
, which i tried, by adding the following lines in front of the find('all'):
$this->Sfile->virtualFields['externalShare'] = $this->Sfile->SfileVersion->virtualFields['externalShare'];
But i get still the same error. I didnt directly understand, what the workaround is doing. Also, my virtual fields may not the problem (active seems to work), just the special one, which points to an other (third) Model association (ExternalShare.id). Does someone have an idea or solution? Thank you very much!

How to fetch rows from hasMany relationship in CakePHP

I have the following Models:
class AppModel extends Model {
public $actsAs = array('Containable');
public $recursive = -1;
}
class City extends AppModel { // for "cities" table
public $belongsTo = 'Country';
}
class Country extends AppModel { // for "countries" table
public $hasMany = 'City';
}
..how do I fetch cities for a country. Something like this I'm trying to find out:
$countries = $this->Country->first(); // fetch a country
$cities = $country->city->find('all'); // get the cities for that country
I've set AppModel in this manner to avoid fetching cities every time I call for a country. Sometimes I don't need all the cities to be retrieved so don't want the default join. But, there are times I do want to fetch cities for a given country. The following is the only way I know how:
$cities = City->find('all', array(
'conditions' => array(
'City.country_id' => $country['Country']['id']
)
))
Is this the most convenient way to access cities once relationships have been established in the model? If so, I don't really understand why bother with $belongsTo and/or $hasMany. Thanks
Associated models first will find the main model, and then will find associated models based on the first query. So it's impossible to limit them based on associated model conditions. So, if you want to limit the main model based on the associated model, you have two options:
Do a Join find
Do a reverse find. It means that you can find City based on conditions, and contain the Country associated to it. For example (assuming that you're on CountriesController):
$this->Country->City->find('all', array(
'conditions' => array(
//your conditions
),
'contain' => array('Country')
));
As you are using CakePHP Model relationship, then it's not require to write Join query.
First thing add the following in Model of Country
class Country extends AppModel { // for "countries" table
public $recursive = 1;
public $hasMany = 'City';
}
Just write the following code,
$countries = $this->Country->find('all');
You can get the cities from $countries in an array format.

Cakephp inheritance of model associations

If I create a Model Car with some associations:
hasOne Driver
hasMany Wheel
And then create a Model Truck extending Car with
class Truck extends Car { ... }
is it normal that the associations from Car are not inherited from Truck?
What are the possibilities to inherit model associations?
Thanks in advance!
Inheritance is PHP related; your custom classes will behave the same way regardless of anything in cakephp. Class inheritance in CakePHP is completely depended on How your classes are written. Inheritance is an important part of cakephp; the framework is very much object oriented.
Are you including the classes properly using App::uses() to load your car class into truck?
The only way your Truck class will not inherit from the Car class is if you have defined the properties in the Truck class.
class Car extends AppModel {
public $hasOne = array('Driver', ...);
}
class Truck extends Car {
public $hasOne = array(); // now you have no hasOne relations
}

CakePHP Unit belongsTo Complex, but not all Unit has Complex?

I have a 'Complex' model which hasMany Unit. My model associations are correct, everything works, it's just that I am having trouble getting a different model/association working correctly and it has made me wonder if I need to set this model up differently.
See, not ALL Unit will have a Complex associated with it. Some Unit are houses, some Unit are hotel rooms, and some Unit are just rental companies.
Because Complexes haveMany Units I am tempted to leave it alone, but I am wondering if I shouldn't redefine the relationship as Complex belongingTo Unit. I am trying to not repeat myself in my database with adding in multiple instances of the same complex.
Here is my current Unit Model:
class Unit extends AppModel {
public $name='Unit';
public $belongsTo=array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user'
),
'Complex'=>array(
'className'=>'Complex',
'foreignKey'=>'complex_id'
)
);
public $hasOne=array(
'Location'=>array(
'className'=>'Location',
'foreignKey'=>'location_id'
)
);
}
and here is my current Complex model:
class Complex extends AppModel {
public $name='Complex';
public $hasMany=array('Unit');
public $hasOne=array(
'Location'=>array(
'className'=>'Location',
'foreignKey'=>'location_id'
)
);
}
By the way, 'Location' is the model I am having trouble with (the Location part of my array currently returns empty when I call my unit/complex information in my view, so I need to get my association right).
If the Unit is a condo with a complex, I want it to return the Location of Complex. If it is a house or hotel or rental company, I want it to return the Location of Unit. I have to do several of these associations (images, location, and so forth) so I want to get everything straight right up front.
Is my current relationship between Unit and Complex correct or do I need to define everything differently?
UPDATE Here is my controller logic:
$this->paginate['Unit']=array(
'limit'=>9,
'order' => 'RAND()',
'contain'=>array(
'User'=>array(
'email'),
'Complex'=>array(
'id','complex_name', 'realname', 'photo1','photo2','photo3','photo4','photo5'),
'Location'=>array(
'complex_id','address', 'city','state','zip','area_code','exchange','sln','lat','lon','website')
),
'conditions'=>array(
'Unit.type'=>array('condo', 'rentalco'),
'Unit.active'=>1)
);
$data = $this->paginate('Unit');
$this->set('allcondos', $data);
}
And you can see the result I get here:
I am not currently interested in displaying a view of all Complexes, but the index page logic does have ContainableBehavior limited to just Complex(as originally I was going to have views for various Complexes):
public function index() {
$this->Complex->Behaviors->attach('Containable');
$this->Complex->contain();
$c=$this->Complex->find('all');
$this->set('complexes', $c);
}
UPDATE I have it working now, for anyone who encounters this problem. I had to change Location to the root and make Complex belongTo Location. Here are my models updated:
class Location extends AppModel {
public $name='Location';
public $hasMany=array('Complex', 'Unit');
var $belongsTo=array(
'Restaurant'=>array (
'className'=>'Restaurant',
'foreignKey'=>'restaurant_id'
)
);
}
class Complex extends AppModel {
public $name='Complex';
public $hasMany=array('Unit');
public $hasOne=array('Image');
public $belongsTo=array(
'Location'=>array(
'className'=>'Location',
'foreignKey'=>'location_id'
)
);
}
class Unit extends AppModel {
public $name='Unit';
public $belongsTo=array(
'User'=>array(
'className'=>'User',
'foreignKey'=>'user'
),
'Complex'=>array(
'className'=>'Complex',
'foreignKey'=>'complex_id'
),
'Location'=>array (
'className'=>'Location',
'foreignKey'=>'location_id'
),
);
public $hasOne=array('Image');
}
Many thanks to Wylie for the help, this was a doozy!
http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html?containing-deeper-associations#containing-deeper-associations
When using ‘fields’ and ‘contain’ options - be careful to include all foreign keys that your query directly or indirectly requires. Please also note that because Containable must to be attached to all models used in containment, you may consider attaching it to your AppModel.
You can do that in your AppModel like this: public $actsAs = array('Containable');
You don't have to use Contain when you don't want to so it shouldn't get in the way.
When a model A has model B, you use the foreign key within model B. So your foreign key on the Location should be complex_id. Although, that shouldn't be so because not all units have a complex.
It seems to me you should make the Location the "root". So, Complex belongsTo Location and Unit belongsTo Complex and Location. Then Location hasOne/Many complex, etc. Either that or just put the address columns in the Unit/Complex tables.

Resources