I feel pretty darn dumb posting this question, but im completely baffled (probably because im quite new to cake and a bit intimidated)..
hasOne hasOne
donors | blood_groups | donor_types
Att ------------------+-----------------------+---------------------+
DonorID (pk) | blood_group_id (pk) | type_id (pk) |
Name | group | type |
Surname | | |
type_id(fk) | | |
blood_group_id(fk)| | |
The Donor Model
class Donor extends AppModel{
public $hasOne = array(
'BloodGroup'=> array(
'className' => 'BloodGroup'
),
'DonorType' => array(
'className' => 'DonorType'
)
);
I am already using the assoctiated models to populate a an FormHelper input in the donor registration view, all is good.
However when I try to retrieve a donor record this error occurs
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column
'BloodGroup.donor_id' in 'on clause'
This ofcours means that cakePHP is looking for the fk donor_id inside blood_groups table. However the relationship is the other way around and the fk is stored within donors table.
I do not know whether the db design is flawed or if the association needs to be redefined within cake. please help, as I am quite new to cakePHP and I a practically forced to use it because of its merits.
I have read all the section about Association between models in the cake doc, but I am still struggling. How can I go about this?
To get this database setup, which is correct working the assocs would be:
Donor belongsTo BloodType
Donor belongsTo DonorType
BloodType hasMany Donor
DonorType hasMany Donor
But your foreign keys are wrong: Follow the CakePHP conventions!
Model fields are supposed to be lower cased and underscored, PKs are expected to be just id and FKs are the model name of the assoc, singular, underscored with suffix _id. The PKs in the donors table are right.
Why are you even changing your own convention? DonorId vs blood_group_id as PKs? However, if you want to cause a mess name them like you want but you'll have to declare them explicitly then everywhere. See linking models.
I recommend you to do the blog tutorial before messing with the framework to get a real project done.
Change your Donor model as shown below:
I have added foreignKey in BloodGroup and conditions in DonorType:
class Donor extends AppModel{
public $hasOne = array(
'BloodGroup'=> array(
'className' => 'BloodGroup',
'foreignKey' => 'blood_group_id'
),
'DonorType' => array(
'className' => 'DonorType',
'conditions' => array('Donor.type_id' => 'DonorType.type_id')
)
);
Reason for above error: If foreignKey is not defined in association array then CakePHP assumes that tablename_id is foreignKey.
Related
I am new to CakePHP and building my first web project for customer service request.
I have following tables in database...
customers
customer_addresses
customer_service_requests
service_requests
service_requests table has foreign keys:
customer_id
customer_address_id
While baking MVC for service request, I'm getting following errors
Error: Table customers_addresses for model CustomerAddress was not found in datasource default.
The ServiceRequest model has a belongsTo relation as
'CustomerAddress' => arrray(
'className' => 'CustomerAddress',
'foreignKey' => 'customer_address_id',
'conditions' => ' ',
'fields' => ' ',
'order' => ' '
)
cakephp version : 2.7.8
Looks like according to the convention, they are expecting the databse table name to be customers_addresses for the model CustomerAddress .
You have two options.
Either modify your database table name to customers_addresses.
Create a model CustomerAddress.php and write the following line within your model.
class CustomerAddress extends AppModel{
public $useTable = "customers_addresses";
}
Peace! xD
I have the following tables:
teams(id, name)
team_users(id, team_id, user_id)
users (id, username)
projects (id, project_name, team_id)
A team hasMany users, Users hasMany teams, a project belongsTo a team.
If I call $this->User->find(); It returns the information of the user and the team's he belongs to.
What I want to do is, I would like to get a count of the projects he is associated with. Meaning:
John Doe is a member of Team X and Y. X has 2 projects and Y has 3 projects. I would like to return number of projects as 5, some sort of virtual field. Is it possible?
If you had properly set up you model relationship this query is all you need:
$this->User->virtualFields = array('total_projects' => 'COUNT(*)');
$user_projects = $this->User->find('all',array('fields' => array('total_projects', '*')));
//$user_projects["User"]["total_projects"] -> this will result to 5 base on your question above or you can debug this by: debug($user_projects) so you can see the content of the array
Use the "counterCache" option in the relation.
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
class Project extends AppModel {
public $belongsTo = array(
'Team' => array(
'className' => 'Team',
'foreignKey' => 'team_id',
'counterCache' => true
)
);
}
You'll need to add a new field project_count to your teams table, CakePHP will do the rest.
This is with CakePHP 2.4. I have a table (table1) which is connected to three others (tables 2 to 4) through a hasMany through connection. All four tables are in a non-default database. Although I'm using hasMany from tables 2-4 to table 1 and in the class for table1
public $belongsTo = array('table2', 'table3', 'table4');
When I try and display the view for table1 I get the error
Table table1 for model model1 was not found in datasource default
So it's looking in datasource default even though all four tables have are in the non-default database (specified using $useDbConfig).
Although the documentation doesn't say why you would want to specify the classname, even if it follows the naming convention, this appears to be the solution:
public $belongsTo = array('table2', => array(
'className' => 'table2'),
'table3'=> array(
'className' => 'table3'),
'table4'=> array(
'className' => 'table4'));
I'm having trouble setting up friendships with CakePHP 2.
I have two database tables: users and friends. My users table has the following columns:
id
email
password
And my friends table has the following columns:
id
user_id
friend_id
approved
I have friends set up as a hasAndBelongsToMany relationship in my Users model:
<?php
class User extends AppModel {
public $hasAndBelongsToMany = array(
'Friends' => array(
'className' => 'User',
'joinTable' => 'friends',
'foreignKey' => 'user_id',
'associationForeignKey' => 'friend_id',
'unique' => true
)
);
}
Now, when I try and retrieve friends for a user, it only lists friendships that the specified user initiated, i.e. where user_id is equal to the user ID; it doesn't show me friends where the other person may have initiated the request (i.e. where the current user's ID is in the friend_id column).
How can I fetch friends, so records where either the user_id or friend_id column is equal to a particular ID?
I don't think you understand how HABTM works. Read this part of the book. You will need a friends_users table in addition to the tables you have for the relationship to work. I think if you were going to set it up this way, you'd need to define a Friendship as having and belonging to many Users.
However, I question whether with your current setup you want a HABTM relationship. It seems like a user hasMany friends, and that's it. Look into using that relationship, and it'll give you the relevant ID as you expect it to. Don't forget to define Friend belongsTo User.
Here beings my canonical Cake 2.0 Friendship tutorial. I downloaded cakePHP 2.1 so I had a fresh start. I first changed my security salt and cipher, then added my database connection. Then I structured my database as follows:
Database:
users table:
id | int(11)
created | datetime
username | varchar(255)
friendships table:
id | int(11)
user_from | varchar(255)
user_to | varchar(255)
created | datetime
status | varchar(50)
Obviously, your users table can/will have more stuff, but this is the minimum I needed.
Models:
Okay this is the tricky part. Here are the relationship I defined in my User model.
class User extends AppModel {
/* Other code if you have it */
var $hasMany = array(
'FriendFrom'=>array(
'className'=>'Friendship',
'foreignKey'=>'user_from'
),
'FriendTo'=>array(
'className'=>'Friendship',
'foreignKey'=>'user_to'
)
);
var $hasAndBelongsToMany = array(
'UserFriendship' => array(
'className' => 'User',
'joinTable' => 'friendships',
'foreignKey' => 'user_from',
'associationForeignKey' => 'user_to'
)
);
/* Again, other code */
}
Here is my Friendship model:
class Friendship extends AppModel {
/* Other code if you have it */
var $belongsTo = array(
'UserFrom'=>array(
'className'=>'User',
'foreignKey'=>'user_from'
),
'UserTo'=>array(
'className'=>'User',
'foreignKey'=>'user_to'
)
);
/* Again, other code */
}
Note on models: The friendship model belongs to 2 users. The user model has 3 associations. The two hasMany relationships in the User Model are both aliases for the accessing the Friendship model's data, so we can use $this->User->FriendTo or $this->User->FriendFrom from controllers to get to the Friendship model. I at first called these UserFrom and UserTo, mirroring the setup of the Friendship model, but Cake threw a hissyfit about similarities, so I had to make them more distinct.
Controllers and Views:
I baked controllers and views using the bake utility. I then created two users (Daniel and Martin) and created a new friendship from Daniel to Martin with a status of requested. I then updated the friendship status to confirmed.
I created the following viewless custom user action to demonstrate data retrieval about a friendship from the UsersController:
public function test() {
$data = $this->User->FriendFrom->find('all',
array(
'conditions'=>array('user_from'=>1),
'contain'=>array('UserTo')
)
);
die(debug($data));
}
This find uses the hasMany relationship of the UserModel to access the Friendship model and get the related user_from and user_to data for the relationships where the user with the id of 1 initiated the relationships.
Your specific find:
Martin, the find you're looking for is super simple under this system, and while you could do it differently, you'd always be dealing with a similar method, simply as long as there are always two sides to a relationship. All you have to do is get a list of relationships where your user ID is either user1 or user2 (in my case, just so I know who initiated the relationship, I have them stored as user_to and user_from- I think this is what intimidated you). Then I iterate through the whole array, selecting the relevant friend data based on whether I am user1 or 2 in that given array. It's a really simple method, and I just put it in my user Model. Change the die(debug()); to return $friendslist to be able to call it from your controller and get an array back.
public function getFriends($idToFind) {
$data = $this->FriendFrom->find('all',
array(
'conditions'=>array(
'OR'=> array(
array('user_to'=> $idToFind),
array('user_from'=> $idToFind)
)
)
)
);
$friendslist = array();
foreach ($data as $i) {
if ($i['FriendFrom']['user_from'] == $idToFind){
$friendslist[] = $i['UserTo'];
}
elseif ($i['FriendFrom']['user_to'] == $idToFind){
$friendslist[] = $i['UserFrom'];
}
}
die(debug($friendslist));
}
I have a ProductsController in which I am retrieving Products data and need to also retrieve the Category Name. (Note: My Products table has only Category_ID in it), how can I do that using CakePHP model associations?
I have seen examples in which the ID of the main data table (in my case, Products table) is a Foreign Key in the Associated Table. However, my case slightly different in that the Category_ID (from the secondary table) is part of the Main table (Products table).
I am not able to retrieve the Category Name using CakePHP model config. Can you help?
My ProductsController is on Products table which has
ID
Prod_Name
Category_ID
....
My Categories table is like
ID
Cat_Name
In my ProductsController I want to retrieve Cat_Name for Products being retrieved.
In your Product Model, use the association:
var $belongsTo = array(
'Category' => array(
'className' => 'Category',
'foreignKey' => 'category_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
When retrieving your Products data use find method:
$this->set('variable', $this->Product->find('all'));
Once its in your View, it is an array containing all the products and its category.
Like this:
<?php
foreach($variable as $itemInTable):
echo 'Product:' . $itemInTable['Product']['Prod_Name'];
echo 'Its Category:' . $itemInTable['Category']['Cat_Name'];
endforeach;
?>
fzmaster's answer is correct. When you have a foreign key in Table A that corresponds to an id in Table B, it is said that the Model A "belongs to" Model B. At the same time, there could be an inverse relationship where Model B "has many" Model As.
The associations are fairly straightforward within that context and if you use the Cake naming conventions, you can associate the models with minimal additional code:
class Product extends AppModel{
var $belongsTo = array( 'Category' );
}
class Category extends AppModel{
var $hasMany = array( 'Product' );
}
At that point, CakePHP's Model::Find() method will automatically retrieve associated models unless you limit it with $recursive or by using the Containable behavior.