Beginning CakePHP: Chapter 4 Solution

Meta: February 12th 2009 // CakePHP // 57 views

At the end of chapter 4 there is a challenge:

You may have noticed that I left the commentstable out of the tutorial for this chapter.This was to allow you to try
building a “has many”relationship for the postsand commentstables on your own.In this exercise,associate
comments with posts by using the appropriate relationship,and test the association using the scaffold.Be sure to
check for errors by running the controller from both ends of the association.

Don’t forget to add the Belongs To relationship. In a one to many relationship, or $hasMany, you need to specify this way: Posts $hasMany comments but comments $belongsTo posts! So i would then have:

Model: post.php

class Post extends AppModel {
  var $name = 'Post';
  var $belongsTo = array(
    'User'=>array(
      'className'=>'User',
      'foreignKey'=>'user_id',
      'conditions'=>null,
      'fields'=>null
    )
  );
  var $hasAndBelongsToMany = array('Tag');
  var $hasMany = array('Comment');
}
?>

Model: comment.php

class Comment extends AppModel {
  var $name = 'Comment';
  var $belongsTo = array('Post');
}
?>

Tags: , , ,

WeDecal.com

Postscript: Leave A Comment // Subscribe (RSS Feed)

Want To Be Heard? Comment Here!

// I Love Comments, Especially Nice Ones

Who Are You?

Your Email Address

Your Website

:D :) :o :eek: :( :lol: :wink: :arrow: :idea: :?: :!: :evil: :p

You can follow any responses to this entry via its RSS comments feed. You may also leave a trackback by clicking this link.