I am developing a web app for an art gallery, and I want to check I have set up the data model correctly.
I have a people table and an artists table. Some of the people are artists and some are not.
I also have a products table and each product belongs to one artist.
Below is a simplified version of the tables:
products
********
id
title
artist_id
artists
*******
id
profile
rating
person_id
people
******
id
first_name
last_name
I need to be able to retrieve the name of the artist when performing the find() method on the Product model.
Have I set up the data model correctly and if so what is the best way to retrieve the artist's name without getting lots of unwanted data?
It's possible to use CakePHP's bindModel & unbindModel to build up relations that don't rely on Cake's automagic goodness.
Since you were interested in doing the find on the Product model, I'll set out an example that can be called from the Products controller:
// unbind Artist
$this->Product->unbindModel(array(
'belongsTo' => array('Artist')
));
// bind Artist & Person using explicit conditions
$this->Product->bindModel(array(
'hasOne' => array(
'Artist' => array(
'foreignKey' => false,
'conditions' => array('Artist.id = Product.artist_id')
),
'Person' => array(
'foreignKey' => false,
'conditions' => array('Person.id = Artist.person_id')
),
)
));
// return the person
$person = $this->Product->find('first', array(
'conditions' => array(
'Product.id' => 1 // or any other condition
),
'fields' => array(
'Person.first_name',
'Person.last_name'
)
));
What's happening here?
Firstly, we unbind the Product model's relationship with the Artist model.
Secondly, we bind the Artist and Person models by explicitly defining the relationships and disabling Cake's automatic forigenKey connections.
Lastly, we do a 'first' find on the Product model and only request the 'first_name' & 'last_name' of the Person.
Each 'Product' belongs to an 'Artist' and each 'Artist' hasAndBelongsToMany 'Product'
You will also need the following table:
artists_products
****************
id
product_id
artist_id
http://book.cakephp.org/#!/view/1044/hasAndBelongsToMany-HABTM
Related
Lets say each book has AuthorA and AuthorB fields.
Both fields are foreign keys for authors table.
table authors with fields: id | name
table books with fields: id | name | a_author_id | b_author_id |
How should controller, model and view be set up to be able to create a book with dropdown list of "author a" and "author b" both coming from author table? How would form-input for author-a (and author-b) look like inside "Add" view for Book model?
You need to setup 2 belongsTo association in your Book model with different aliases for Author model.
public $belongsTo = array(
'AAuthor' => array(
'className' => 'Author',
'foreignKey' => 'a_author_id'
),
'BAuthor' => array(
'className' => 'Author',
'foreignKey' => 'b_author_id'
)
);
Use $this->Book->AAuthor->find('list') to get the authors list and set the array to view and specify same array using 'options' key in Form->input() options for both a_author_id and b_author_id fields.
Assume we have 3 models, User, House and Profile with the following associations between them:
User hasMany House (House belongsTo User)
User hasOne Profile (Profile belongsTo User)
I would like to query for houses (inside the HousesController class), whose associated Profiles satisfy the given Profile conditions. Consider the following example:
Assuming that gender is a property of Profile model, I would like to retrieve all the houses, whose owner is male.
I have found this question, which is close enough to what I seek for. In my case, the relationship between models is more complex (House belongsTo User hasOne Profile) and I can't get it to work. I have tried something like this, without any luck:
$this->House->find('all', array(
'contain' => array(
'User' => array(
'Profile' => array(
'conditions' => array(
'Profile.gender' => 'male'
))))));
The above call returns all the houses and in case the gender is male, it includes the respective User's Profile in the result. Otherwise, the User's Profile remains empty. What exactly I need is to return only the houses whose owner is male.
I have actually implemented it using the 'joins' option of Model::find() function, but I would like to know whether is this possible without using 'joins' and if yes, how?
I would recommend explicitly declaring the relationships using the bindModel method.
You could do this from your Houses controller like so:
/**
* Bind the models together using explicit conditions
*/
$this->House->bindModel(array(
'belongsTo' => array(
'User' => array(
'foreignKey' => false,
'conditions' => array('House.user_id = User.id')
),
'Profile' => array(
'foreignKey' => false,
'conditions' => array('Profile.user_id = User.id')
)
)
));
/**
* Standard find, specifying 'Profile.gender' => 'male'
*/
$houses = $this->House->find('all', array(
'conditions' => array(
'Profile.gender' => 'male'
)
));
I'm trying to figured out what's the best way to make a "Has One Belong to One" relation in CakePHP. Unfortunatly I didn't found anything for helping me on the internet.
I've tried to proceed like that:
Company model :
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
User model :
var $hasOne = array(
'Company' => array(
'className' => 'Company',
//'foreignKey' => 'user_id',
'dependent' => true
)
);
But still cakePHP allow me to create two companies for one user.
And here my database schema :
Company : id, name, ..., user_id
User : id, name, ...
Many thanks
CakePHP can handle the following relationships only:
one to one
one to many
many to one
many to many
Read more here
If you want to do "Has One Belong to One" then use the hasOne feature in both objects.
If each user has only one company and each company belongs to one and only one user, shouldn't they be on the same table?
like:
USER
Id
Name
...
Company
Sorry if I shouldn't ask questions back here but seemed pertinent.
In your database, company table, user_id should be set unique.
I have the following three database tables:
Products
########
id
title
artist_id
Arists
######
id
profile
person_id
People
######
id
first_name
last_name
In my Product model how do I create a method to return the product title along with the artist's first_name?
I have set up the following model associations:
Product belongs to Artist
Artist belongs to Person
Containable is definitely the way to go for filtering related records. Make sure to add $actsAs = array('Containable') into your model or app_model.
Then you can do things like:
$this->Product->find('all', array(
'contain' => array(
'Artist' => array(
'Person' => array(
'id',
'first_name'
)
)
)
));
Assuming you already set the relationships in these models, you just need to set it recursive:
$this->Product->recursive = 2;
print_r($this->Product->find('all'));
When I was working on my current project, I ran into a rather complex issue. I'll point out my problem much more detailed right now:
There are three Models: User, UsersExtendedField and UsersExtended.
UsersExtendedField contains custom fields that can be managed manually. All custom fields can be shown in the Users view as well, and be filled out of course. The values are then stored in UsersExtended, which has got two foreignKeys: user_id and field_id.
The relations look like this: User hasMany UsersExtendedField, UsersExtendedField hasMany UsersExtended, UsersExtended belongsTo User, UsersExtendedField.
The problem: When accessing the Users view, a form with user information input is shown. Any UsersExtendedFields are available as well, and since these hasMany UsersExtended, they've got plenty of UsersExtended values. But I want to reduce those to only the value(s) that belong to the User, whose view is shown at the moment. Here are my (desired) relations:
Croogo::hookBehavior('User', 'Crooboard.ExtendedUser', array(
'relationship' => array(
'hasMany' => array(
'UsersExtendedField' => array(
'className' => 'Crooboard.UsersExtendedField',
'foreignKey' => '',
'conditions' => array('status' => 1)
),
),
),
));
class UsersExtendedField extends AppModel {
var $name = 'UsersExtendedField';
var $displayField = 'fieldname';
var $hasMany = array(
'UsersExtended' => array(
'className' => 'Crooboard.UsersExtended',
'foreignKey' => 'field_id',
'conditions' => array(
'UsersExtended.user_id = User.id'
)
),
);
}
This is not the full code, these are the important parts. The problem starts right where I wrote 'UsersExtended.user_id = User.id'. Obviously, this won't work. But I do not have any idea how to access the User.id here. I also could not imagine a HABTM structure to solve this task. Do you have any idea how to get the semantics of this 'UsersExtended.user_id = User.id' to work?
Thank your very much for taking the time to read through this and helping me!
It sounds like you need to set up your HABTM relationship properly.
You already have the join table, UsersExtended, which contains your foreign keys.
Remove all previous relationships and set up HABTM in each of your User and UserExtendedField models.
The relationship code in your User model would look like this:
var $hasAndBelongsToMany = array(
'UsersExtended' => array(
'className' => 'UsersExtended',
'joinTable' => 'UsersExtended', //assuming this is the
//name of that model's table
'foreignKey' => 'user_id',
'associationForeignKey' => 'field_id'
)
);
For more information check out the page in the cakephp book
In addition, this blog post helped me grasp the relationship concepts when I was learning cakephp.