CakePHP Unit belongsTo Complex, but not all Unit has Complex? - cakephp-2.0

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.

Related

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.

Table not found, same using useTable

I have a model, called "Cliente" and this model have a association with another table called ClienteRelFot. I declared that ClienteRelFot has a useTable = 'rel_fot_ec', but the cake are looking for "rel_fots".
The rel_fot_ec table exists on my database because I use to find another data.
Someone have a idea to solve this problem?
I tried clear cache and delete all files from tmp folders.
Below, we have the error:
Error: Table rel_fots for model RelFot was not found in datasource default.
Your associations are trying to pull data from the model 'RelFot' (per the error), not 'ClientRelFot', so declaring that 'ClienteRelFot' uses the table 'rel_fot_ec' will have no effect.
Try adding:
public $useTable = 'rel_fots';
in your 'RelFot' model.
I had this problem too, even though using public $useTable = ...
My data model: Event hasMany > Submissions hasMany > Authors
Cake was telling me [MissingTableException] Table authors for model Author ..., the problem was not in the Author model, but in the Submission model:
class Submissions extends AppModel {
public $hasMany = array(
'Author' => array(
'className' => 'authors', // author should be singular
'foreignKey' => 'submission_id'
)
);

CakePHP: To Create A New Controller

I'm using CakePHP 2.0.5 (but this isn't necessarily a cakephp specific question). I have a Coupon and a User model. Each time a user prints a coupon (proccessed by: Coupon Controller):
class CouponsController extends AppController {
public function printcoupon($id = null) {
// code
}
}
I want to save the information to a "coupons_printed" table (id/coupon_id/user_id/created). Should I create a new model for this, or should I just create a function inside of the Coupon model similar to (and call it in the controller each time that page is viewed)?:
class Coupon extends AppModel {
function insertIntoPrinted($id) {
$this->query("UPDATE coupons_printed SET .....");
}
}
Whatever you do, a raw SQL query is not the best way to go. Always use CakePHP methods if at all possible (and almost always it is possible).
You should put the insertIntoPrinted() function in the CouponsPrinted model (although, as a side note, PrintedCoupon would be a more natural way to name the model...) You can then add a HasMany relationship to the Coupon model ($hasMany = array( 'CouponsPrinted' )) and call the function in the CouponsController:
public function printcoupon($id = null) {
$this->Coupon->CouponsPrinted->insertIntoPrinted( $id );
}
CakePHP's model has a thing call association.
In your case, Coupon has a hasMany association with coupons_printed.
You can create a new model, or query using the association in the Coupon model, the generated queries will be the same, I believe.
Your CouponsController already depend on Coupon Model, so not creating another model is a better solution.

CakePHP: calling other Model functions

How can i call, from a Model, a function present in another model? I would like not to repeat code.
We can use Model relation to call the function in another model. Eg.
$this->Model->ModelOne->find();
$this->Model->ModelOne->customFunc();
If there is no relation in the models, The we can use
$this->loadModel('ModelName');
To use in the model.
In this case you can use
$this->ModelName->function();
directly as you've loaded that model.
You should try to have relationships between your models. There are many types of relationships which you can read here...
If you have above said associations, you can access your associated models using:
$this->Model->OtherModel->function();
If your models are not related in any way, you should use:
ClassRegistry::init('OtherModel')->function();
You can check out my question on this where I obtained great answers
User App::import()
App::import('Model','OtherModel');
$attr = new OtherModel();
$attr->Othermodelfunction();
if there's a (direct or indirect) relationship between the model, you can call the function: $this->Model1->Model2->...->Modeln->function();
use bindModel
no, you should use ClassRegistry like so:
//MessagesController - in my send() method...
$this->set('content', ClassRegistry::init('Content')->find('first', array(
'conditions' => array('Content.id' => 3)
)));
NOTE:this is from my controller but I am pretty sure it works in model too.
In 2.x versions the $this->Model1->Model2 syntax answered above will not work. Calling functions from another models in many cases is the job of a controller, not the model. Consider that, the model methods should be limited to querying and updating data whilst maintaining database integrity.
1st method: using the controller
I'll illustrate this with an example of Firm and User models, while Firm hasMany users. This method is recommended, if you plan to add extra controller functionality inbetween, such as setting flash messages or cookies.
User model:
public function saveRegisteredUsers($user_data,$firm_id){ ... }
--
FirmsController:
public function add(){
if($this->Firm->save($this->request->data)){
// set $this->Firm->id here
$this->loadModel('User');
$this->User->saveRegisteredUsers($this->request->data['User'],
$this->Firm->id);
// ...
}
}
2nd method: using the model
For this you will need to have correct model associations. The table names have to be users and firms conventionally. Following the terminology of the example above your relation should be defined as this in the Firm model:
public $hasMany = array( 'User' => array(
'className' => 'User',
));
In the User model, you have to set up the belongsTo association properly:
public $belongsTo = array(
'Firm' => array(
'className' => 'Firm',
'foreignKey' => 'firm_id',
'dependent' => false
)
);
After this, you can call $this->User->saveRegisteredUsers() directly from any of the Firm model methods.
If you have a model function that you want to call from many models, the best approach is to abstract any references to the model name ($this->alias) and place the function in AppModel. Then it is accessible in any of your models.
class AppModel extends Model{
public function myFunction($options = array(){
do some stuff with $this->alias;
}
}

Resources