Skip to content

Instantly share code, notes, and snippets.

@kaptinlin
Created September 26, 2011 19:28
Show Gist options
  • Select an option

  • Save kaptinlin/1243157 to your computer and use it in GitHub Desktop.

Select an option

Save kaptinlin/1243157 to your computer and use it in GitHub Desktop.
lithium mysql hasMany relationship add unwanted data when no relationship data.
<?php
namespace app\models;
class Comments extends \lithium\data\Model {
public $validates = array();
}
?>
CREATE TABLE `comments` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`post_id` int(11) NOT NULL,
`comment` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
-- --------------------------------------------------------
CREATE TABLE `posts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Posts table' AUTO_INCREMENT=2 ;
INSERT INTO `posts` VALUES(1, 'This is a sample post');
<?php
namespace app\models;
class Posts extends \lithium\data\Model {
public $validates = array();
public $hasMany = array('Comments');
}
?>
<?php
namespace app\controllers;
use app\models\Posts;
use lithium\action\DispatchException;
class PostsController extends \lithium\action\Controller {
public function index() {
$posts = Posts::all(array('with'=>array('Comments')));
var_dump($posts->to('array')));
/* will output
array(1) {
[1]=>
array(3) {
["id"]=>
string(1) "1"
["title"]=>
string(21) "This is a sample post"
["comments"]=>
array(1) {
[0]=>
array(3) {
["id"]=>
NULL
["post_id"]=>
NULL
["comment"]=>
NULL
}
}
}
}
*/
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment