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.
Related
i'am using cakephp 2.x
i have two tables USERS and JOBS in my database,
in users table i save two types of users job candidate and company in this situation i found my self facing two relations between the tables :
(1,n)users can add (0,1)jobs. (user role here is Company)
many (1,n)users can apply to many (1,n)jobs. ( Candidate)
can i use belongsTo and HABTM(hasAndBelongsToMany) at once between the two models ?
like this :
Job model
Class Job extends AppModel{
public $belongsTo=array(
'User'=> array(
'className' => 'User',
'foreignKey' => 'user_id',
'counterCache'=>true,
'fields'=>array('id','username','role'),
)
);
public $hasAndBelongsToMany=array('User');
public $usetable = 'jobs';
User Model
Class User extends AppModel{
public $hasAndBelongsToMany=array('Job');
how to retrieve data depending on the first or the second context
1- show all jobs of company.
2- show users applies.
You can do this, but the two associations need different aliases. So you could refer to an User appling for a Job as an Applicant:-
class Job extends AppModel {
public $belongsTo = array(
'User'=> array(
'className' => 'User',
'foreignKey' => 'user_id',
'counterCache' => true,
'fields' => array('id', 'username', 'role'),
)
);
public $hasAndBelongsToMany = array(
'Applicant' => array(
'className' => 'User'
)
);
}
Note that you need to tell Cake that the Applicant uses the User model via the className property. For your belongsTo association you don't need to specify the className for the User as it is the same as the alias is the same as the model name but I have left it in for clarity.
You also don't need to specify $usetable = 'jobs as this is implied by using the correct naming conventions.
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
I'm facing trouble telling cake the most simple associations.
I have two Models:
CoreUser.php
CoreRole.php
.
One User has one Role.
How to assign that in cake? (HasOne or BelongsTo? => When to choose what?)
What to put in what Model? I tried both and ever end up with a recursion-error or it is just not working.
My SQL-Tables:
(tbl) core_users [id,username,password,role_id]
(tbl) core_roles [id,name]
My Models:
class CoreUser extends AppModel {
public $hasOne = array(
'Role' => array(
'className' => 'CoreRole',
'foreignKey' => 'id'
)
);
}
class CoreRole extends AppModel {
public $belongsTo = array(
'User' => array(
'className' => 'CoreUser',
'foreignKey' => 'role_id'
)
);
}
=> Can you give me the correct code i need to insert into one of both (or both) models to tell cake about the relationship?
Thanks in advance
Theoretically, there are two things you need to think about, one of them being non-Cakephp specific.
A. Relationships: A relationship is always bidirectional. When determining the relationship between two Models/Objects/Tables, you always ask two questions:
How many instances of B are related to one instance of A?
How many instances of A are related to one instance of B?
You've said, One user has one Role. However, One Role has how many Users related to it? That will tell you the complete relationship between a User and a Role. (Apologies for the digression but this is important and I'm referencing this book.)
B. Difference between hasMany and belongsTo:
This is determined based on the direction of traversing a relationship.
Based on point A, say you've determined that:
One User has one Role but One Role has many Users.
Now when you are in the User's model trying to fetch related Role data, you need to define the following in the User model:
class CoreUser extends AppModel {
public $belongsTo = array(
'Role' => array(
'className' => 'CoreRole',
'foreignKey' => 'role_id'
)
);
}
But when you are in the Role's model and trying to fetch related User data, you will need to define the following in the Role model:
class CoreRole extends AppModel {
public $hasMany = array(
'User' => array(
'className' => 'CoreUser',
'foreignKey' => 'role_id'
)
);
}
For a full discussion refer to this answer.
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');
I have this model and controller and it returns fine if it is a hasOne relationship but now DishCategory hasMany dishes. When I change the code below to hasMany it gives me an error saying Dish.id is not a known column while if it is a hasOne it works fine. How can I make it so that it returns all the Dish.id's that have id=1? (still using the join).
class DishCategory extends AppModel{
public $hasOne = array(
'Dish' => array(
'className' => 'Dish',
'foreignKey' => 'dish_category_id'
)
);
}
class DishCategoriesController extends AppController {
function get_categories($id)
{
// find category with a dish of $id
$this->set('dishes', $this->DishCategory->find('all', array(
'conditions' => array(
'Dish.id' => $id
)
)));
// set master layout
$this->layout = 'master_layout';
}
}
hasOne relations can be joined into the primary SQL query. hasMany relations cannot and need to be queried in a separate query. The conditions you specify for the query only apply to the primary query, all separate relational queries are build just based on the ids retrieved in the primary query. Set debug to 2 and have a good look at the query log to see what I mean.
To find the category of a dish, fetch the dish and look at its related category record:
$dish = $this->Dish->find('first', array('conditions' => array('Dish.id' => $id)));
echo $dish['DishCategory']['name'];
Since I take it that a dish belongsTo one category, your query "find all categories which have a dish with id x" makes little sense; there should only be one anyway.