Dear experts,
How to save or update master-detail in correct ways?
I've added Post and Comment model. But confuse to save or update comments together with a post.
class Posts extends Model
{
/**
* @var integer
*/
public $id;
/**
* @var string
*/
public $date;
/**
* @var string
*/
public $content;
public function initialize()
{
$this->hasMany('id', 'MM\Models\Comments', 'postsId', array(
'alias' => 'comments',
'foreignKey' => array(
'message' => 'Comments cannot be deleted because it has link'
)
));
}
}
class Comments extends Model
{
/**
* @var integer
*/
public $id;
/**
* @var integer
*/
public $postsId;
/**
* @var string
*/
public $body;
public function initialize()
{
$this->belongsTo('postsId', 'MM\Models\Posts', 'id', array(
'alias' => 'post',
'reusable' => true
));
}
}
Here's inside the controller's save function:
$post = new Posts();
$post->date = '2013-09-20';
$post->content = 'Some post here';
$comment1 = new Comments();
$comment1->body = "Some comment 1";
$comment2 = new Comments();
$comment2->body = "Some comment 2";
//
// Now how to append all comments to the post and saving it all together?
//
// $post->comment->add($comment1) ? maybe?
//
$post->save();
I know this is very basic question and this answer is might help another new beginners like me :)
Thank you so much.
Jim