Cakephp belongsTo relationship - accessing related Model - cakephp

I have a consultant table that has a foreign key 'specialty_id' which is linked to a 'specilaties' table.
class Consultant extends AppModel {
public $belongsTo = array(
'Specialty' => array(
'className' => 'Specialty',
'conditions' => array('Specialty.active' => 1)
)
);
}
class Specialty extends AppModel {
public $hasOne = 'Consultant';
}
I think this is right, however, i am unable to get a list of specialties from the consultant controller
("Call to a member function find() on a non-object ")
$this->set('specialties', $this->Specialty->find('all'));
Where abouts am i going wrong?
Thank you

Remember you are in the controller, not in the model. Try this:
$this->set('specialties', $this->Consultant->Specialty->find('all'));

If you are using Model in other controller then, first load that model and then run query:
$this->loadModel('Specialty');

Related

cakephp: how to display foreign key table field

basically,
database table:
Products: id, name
Comments: productId,comment
Model:
product.php
class Product extends AppModel {
public $hasMany = array('Comment'=>array('foreignkey'=>'productId'));
}
comment.php
class Comment extends AppModel {
public $belongsTo = array('Product');
}
In product index.ctp, how can I display one product comment? What I need to write in ProductsController.php and index.ctp?
If you follow the CakePHP conventions (CakePHP Convention over Configuration) then all of this will be done automagically for you, it requires foreign keys to be named product_id rather than productId (although you have setup the foreign key in the relationship - it is just easier to start from the beginning following the conventions).
You should also specify the class name in the relationship:
public $hasMany = array(
'Comment' => array(
'className' => 'Comment',
'foreignKey' => 'product_id'
)
);
In your case what you should do in the controller is:
$products = $this->Product->find('all');
This will fetch all your products and any associated comments on those Products (and also any other associated models you have declared in the Product Model)
If you want to read more about setting this up you can check out CakePHP - Retrieving your data

Model "CartItem" is not associated with model "Product" but it is?

I’m writing a CakePHP plugin. In my plugin’s AppModel I have:
public $actsAs = array(
'Containable'
);
I then have two models: a CartItem and a Product. My CartItem model look like this:
<?php
class CartItem extends ShoppingCartAppModel {
public $belongsTo = array(
'Cart',
'Product'
);
}
However, when calling the Cart model in my controller I get the following error:
Warning (512): Model "CartItem" is not associated with model "Product" [CORE/Cake/Model/Behavior/ContainableBehavior.php, line 344]
Why is this, when I’ve defined that my CartItem model is associated to the Product model through a belongsTo association?
EDIT: I’ve narrowed my problem to where I attempt to fetch my cart and its contents in my Cart model. Here is the call:
public function findBySessionId($sessionId) {
$cart = $this->find('first', array(
'conditions' => array(
'Cart.session_id' => $sessionId
),
'contain' => array(
'CartItem' => array(
'Product'
)
)
));
return $cart;
}
Model associations need a plugin prefix
From the question it is likely the Cart Model is defined like so:
public $hasMany = array(
'CartItem'
);
}
This will mean that Cake is expecting the following:
app
Model
CartItem.php <- 'CartItem' means the model is in the App, not a plugin
Plugin
Model
Cart.php
The App CartItem model doesn't exist, and therefore will be an instance of AppModel.
Always ensure that the plugin prefix is used (if appropriate) when defining model associations:
public $hasMany = array(
'ShoppingCart.CartItem' // Load the model from this same plugin
);
}
Figured out the problem. Models in a plugin need the plugin name in the class name.
For example:
<?php
class Cart {
public $hasMany = array(
'CartItem' => array(
'className' => 'ShoppingCart.CartItem'
)
);
}
Specifying the plugin name just in the association name caused an SQL error for me, so you can circumventing by specifying the class name—with plugin prefix—manually.

CakePHP belongsTo relationship not saving

I have models 'PatientCase' and 'Procedure'. A case can have one/multiple procedures.
class PatientCase extends AppModel {
public $hasMany = 'Procedure';
}
class Procedure extends AppModel {
public $belongsTo = array(
'PatientCase' => array(
'className' => 'PatientCase'
)
);
}
I'm explicitly setting a value in my patientCasesController
$this->request->data["Procedure"]["side"] = 'left';
When i saveAll my patientCase, the case is saved correctly, and a new record is saved in the procedure table, with the corresponding patientCase id, however, no other data is saved in the record.
Can anyone see where i'm going wrong?
Your comment nailed it - save() only saves the main model, while saveAll() saves the main model and any associated models.
save() [details]
saveAll() [details]
Update:
Because it's "hasMany", you probably want:
$this->request->data["Procedure"][0]["side"] = 'left';
(notice the [0])

Cake Relations with diffent name

I got a Table Users and a Table Groups. Every group has one GroupLeader.
So the field i use in is groupLeader ($hasOne) which contains a foreign key of users.
I cant manage to get that relation. So my question is, how to define a relation on a field with a diffent name.
thanks for a hint.
endo
You model should looks:
class Group extends AppModel
{
public $name = 'Group';
public $belongsTo = array('GroupLeader' => array(
'className' => 'User',
'foreignKey' => 'groupLeader'
)
);
}
Try with the above code. And ask if it is not worked for you.

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'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),
...
)
)
}

Resources