简体   繁体   中英

symfony doctrine associations

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.

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM