symfony doctrine associations

2019-07-13 09:02发布

Hi so I managed to get this working for a relationship between users and a Job

I followed exactly the same procedure, checked the documentation and I am at a loss

The relationship i'm trying to set up is Job to work

1 Job with many work items assigned to it

../Entity/Job.php

 /**
 * @ORM\OneToMany(targetEntity="Work",mappedBy="workJob")
 *
 */
protected $jobToWork;
/**
 * Add jobToWork
 *
 * @param \Laelaps\InvoiceBundle\Entity\Work $jobToWork
 * @return Job
 */
public function addJobToWork(\Laelaps\InvoiceBundle\Entity\Work $jobToWork)
{

    $this->jobToWork[] = $jobToWork;

    return $this;
}
/**
 * Remove jobToWork
 *
 * @param \Laelaps\InvoiceBundle\Entity\Work $jobToWork
 */
public function removeJobToWork(\Laelaps\InvoiceBundle\Entity\Work $jobToWork)
{
    $this->jobToWork->removeElement($jobToWork);
}

/**
 * Get jobToWork
 *
 * @return \Doctrine\Common\Collections\Collection
 */
public function getJobToWork()
{
    return $this->jobToWork;
}

../Entity/Work.php

/**
 * @ORM\ManyToOne(targetEntity="Job",inversedBy="jobToWork")
 * @ORM\JoinColumn(name="work_job", referencedColumnName="id")
 */
protected $workJob;

/**
 * Set workJob
 *
 * @param integer $workJob
 * @return Work
 */
public function setWorkJob($workJob)
{
    $workJob->addJobToWork($this);
    $this->workJob = $workJob;

    return $this;
}

/**
 * Get workJob
 *
 * @return integer
 */
public function getWorkJob()
{
    return $this->workJob;
}

I did a app/console doctrine:generate:crud

Which I know worked for my user to job relationship which was set up exactly the same way.

the error I get when I try to go to create a new "work" item is Object of class ..\Entity\Job could not be converted to string

Any help, as always greatly appreciated

UPDATE

As defined in the answer

public function __toString()
{
    return (string) $this->getJobName();
}

As I was using the FOSUserBundle and my user class extended the FOSUser class this meant that the __toString() function was defined in the FOSUser, hence there was no problem when creating assocations to user.

1条回答
我只想做你的唯一
2楼-- · 2019-07-13 09:18

You probably try to display your Job as a string (inside a select box or a list for example). Just add a __toString() method to your Job entity like this :

public function __toString()
{
    return $this->name; // For example
}
查看更多
登录 后发表回答