我有一些问题。我已经研究并尝试了所有的建议,但都无法解决。
最终我得到了以下错误:
实体\User::addCategories() 的第一个参数必须是 Entity\Category 的一个实例,却传递了一个字符串。
我有一个多对多的关系,用户、用户类别和类别
用户
<?php
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @Entity
* @Table(name="user")
*/
class User
{
/**
* @Id
* @Column(type="integer", nullable=false)
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @Column(type="string", length=255, unique=true, nullable=false)
*/
public $name;
/**
* @ManyToMany(targetEntity="Entity\Category", inversedBy="user")
* @ORM\JoinTable(name="user_category")
*/
public $categories;
public function __construct() {
$this->category = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getCategories()
{
return $this->categories;
}
public function addCategories(Category $category = null)
{
$this->categories = $category;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
分类
<?php
namespace Entity;
use Doctrine\Common\Collections\ArrayCollection;
use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;
/**
* @Entity
* @Table(name="category")
*/
class Category
{
/**
* @Id
* @Column(type="integer", nullable=false)
* @GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @Column(type="string", length=255, unique=true, nullable=false)
*/
public $name;
/**
* @ManyToMany(targetEntity="Entity\User", mappedBy="category")
*/
public $user;
public function __construct() {
$this->user = new \Doctrine\Common\Collections\ArrayCollection();
}
public function getUser()
{
return $this->user;
}
public function addUser(User $user = null)
{
$user->addCategory($this);
$this->user = $user;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
插入函数
// check existence object in database
$res = $this->em->find('Entity\User', $this->input->post('id'));
if($res){
$data = $this->em->find('Entity\User', $this->input->post('id'));
}else{
// create a new User object
$data = new Entity\User;
}
$data->setName($this->input->post('name'));
$data->addCategories($this->input->post('category'));
// save the data object to the database
$this->em->persist($data);
$this->em->flush();
在获取方面一切都很顺利,但我对设置工作感到困惑。
谢谢你的帮助。 抱歉我的英语不好。
addCategory
?我已经尝试了各种方法,但仍然遇到错误。 - dhidyboolean given
,并且在D:\WEBSERVER\xampp\htdocs\codetrine\application\models\Entity\category.php on line 66
中出现了“在非对象上调用成员函数addUser()”。 - dhidy