Linking Tables to Cakephp

Asked

Viewed 172 times

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")?

1 answer

1


You should not reference the table of posts by title for the simple fact that more than one post can have the same title, causing an inconsistency in your data model.

Even if you define the title as UNIQUE, Still, it gets weird. The ideal is that both the table of posts and the table of comments have id’s, and the references between the tables are made through id’s.

Your relationship should be like this:

class Post extends AppModel {
    public $hasMany = array(
        'Comment' => array(
            'className' => 'Comment'
        )
    );
}

PS: When to the fk_title, is the reference that the table of posts makes to the comment, in the model proposed in your question.

  • 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?

  • In the class "Comment" concerning the table "Comments" I do the same thing?

  • 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).

  • 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.

  • Thanks! Very useful!

  • If it worked, don’t forget to validate the answer. :)

  • I studied more relationships, was not quite the specific answer to what I wanted to conclude, but helped me find new solutions, thank you.

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.