Relate tables with CakePHP

0

There are two tables in the database, posts and comments and I want to link them together.

I think I have to create a foreign key in the comments table in a field that stores the title or table id posts , so I know which post that comment is .

ALTER TABLE 'comments' ADD CONSTRAINT 'fk_title' 
FOREIGN KEY ('title_id')  REFERENCES 'posts' ('title');

But I have doubts about the CakePHP conventions.

I can use the id field of the posts table, as in the following code, or should I use the title field as I tried to do in the code above?

ALTER TABLE 'comments' ADD CONSTRAINT 'fk_post_id' FOREIGN KEY ('post_id') 
REFERENCES 'posts' ('id');

I have doubts about this fk_title index as well. What is it for?

Once I've created the post_id field in the comments table and made the relationship below:

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

Do I still have to do ALTER TABLE in MYSQL's SQL?

I have to do this same process of $ hasMany within the class Comment (from the Comment.php model created for the comments table)?

    
asked by anonymous 07.12.2014 / 15:29

1 answer

1

You should not reference the posts table by the title simply because more than one post can have the same title, causing an inconsistency in your data model.

Even though you set the title to UNIQUE , it still gets weird. Ideally, both the posts table and the comment tables have id's, and the references between the tables are made through id's.

Your relationship should look like this:

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

PS: When the fk_title , it is the reference that the table of posts does with the one of comment, in the model proposed in your question.

    
07.12.2014 / 15:39