I am just trying to set up a simple parent-child relationship with Doctrine 2 but I am obviously doing something wrong. I am following what it says on the Association Mapping page of the Doctrine website.
I am getting the following errors:
Warning: Invalid argument supplied for foreach() in .../Doctrine/ORM/Persisters/BasicEntityPersister.php on line 1579
Fatal error: Call to a member function setValue() on a non-object in .../Doctrine/ORM/PersistentCollection.php on line 175
Here is my database setup:
CREATE TABLE IF NOT EXISTS `foo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Here is my class:
namespace Classes;
/** @Entity @Table(name="foo") */
class Foo
{
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @OneToMany(targetEntity="classes\Foo", mappedBy="parent_id")
**/
private $children;
/** @ManyToOne(targetEntity="classes\Foo", inversedBy="children")
* @JoinColumn(name="parent_id", referencedColumnName="id")
**/
private $parent;
public function __get($name)
{
if(property_exists($this, $name)){
return $this->$name;
} else {
throw new \Exception('Field "' . $name . '" does not exist.');
}
}
}
and here is the page that calls it:
$server = '/Applications/XAMPP/htdocs/projects/Scratch';
require_once $server . '/Model/bootstrap.php';
$myFoo = $em->find('classes\Foo',37);
echo $myFoo->id . '<br />';
echo count($myFoo->children);
I can't seem to find this myself, but are namespaces in PHP case sensitive?
The other thing that I've seen used when setting up these kinds of relations is the instantiation of a collection in the entity constructor. This would apply specifically to the children property.
Hope this helps.
While not an answer, here is a work around...
You can use:
$children = $em->getRepository('classes\Foo')->findby(array('parent_id',parentID);