0
There are two tables in the database, posts and comments and I want to relate them.
I think I have to create a foreign key in the table comments in a field that holds the title or table id posts, so I’ll know which post that comment is from.
ALTER TABLE `comments` ADD CONSTRAINT `fk_title`
FOREIGN KEY (`title_id`) REFERENCES `posts` (`title`);
But I have doubts because of Cakephp’s conventions.
I can use the field id table posts, as in the following code, or should I use the title as I tried to do in the above code?
ALTER TABLE `comments` ADD CONSTRAINT `fk_post_id` FOREIGN KEY (`post_id`)
REFERENCES `posts` (`id`);
I doubt that index fk_title too. What’s the point?
Once I’ve created the field post_id on the table comments and made the relationship below:
class Post extends AppModel {
public $hasMany = array(
'Comment' => array(
'className' => 'Comment'
)
);
}
I still have to do ALTER TABLE in MYSQL SQL?
I have to do this same process of $hasMany within the class Comment (model Comment.php created for the "comments table")?
Could you look at my edition? I thank you for your answer. In the case inside the Model Post I have to use $hasMany to inform that the posts table has foreign key in the comments table?
– I Wanna Know
In the class "Comment" concerning the table "Comments" I do the same thing?
– I Wanna Know
If the Post class "has many" comments, of course the Comment class "belongs to" (
belongsTo
) Post class (and not "own many" Post’s, as you asked).– Rodrigo Rigotti
As for changing your model, I can’t answer because I don’t work with Cakephp. But I know that putting relationships into both models and changing the foreign key already corrects what was wrong with your model.
– Rodrigo Rigotti
Thanks! Very useful!
– I Wanna Know
If it worked, don’t forget to validate the answer. :)
– Rodrigo Rigotti
I studied more relationships, was not quite the specific answer to what I wanted to conclude, but helped me find new solutions, thank you.
– I Wanna Know