我只是試圖與教條2建立一個簡單的親子關係,但我顯然做錯了什麼。我遵循Doctrine網站的Association Mapping page上的說法。學說父母孩子找到無效的Foreach
我收到以下錯誤:
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
這裏是我的數據庫設置:
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 ;
這裏是我的類:
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.');
}
}
}
這裏是調用的頁面它:
$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);
真棒的想法。命名空間的情況不會導致問題。據我所知,它沒有任何區別,我的呼叫頁面確實輸出正確的ID。 –
對於構造函數,根據這裏的答案:http://stackoverflow.com/a/4779225/133935 find不會調用__construct()。如果在加載後調用__construct()並初始化集合,則錯誤消失,但我會按預期丟失所有關係。 –