I have an table Article that is in relationship with Steps (OneToMany) and Steps with Article ManyToOne.
I get Articles with:
$articles = $this->getDoctrine()
->getRepository("IftodiDesignBundle:Article")
->findAll();
And with foreach I want to show all Articles and Steps:
foreach($articles as $article)
{
$steps = $this->getDoctrine()
->getRepository("IftodiDesignBundle:Steps")
->createQueryBuilder('s')
->where('s.article = \''.$article.'\'')
->getQuery()
->execute();
echo "<b>".$article->getTitle()."</b><br />";
echo $article->getText()."<br />";
}
I don’t know how to get data from table Steps usign the table Article and method getSteps() that is generated with Doctrine.
Please help me.
Thanks for the answer.
In table Article I have:
/**
* @ORM\OneToMany(targetEntity="Steps", mappedBy="Steps",cascade={"persist"})
* @ORM\JoinColumn(name="id", referencedColumnName="id_article")
*/
protected $steps;
In table Steps:
/**
* @ORM\ManyToOne(targetEntity="Article", inversedBy="steps")
*
*/
protected $article;
When I do:
$articles = $this->getDoctrine()
->getRepository("IftodiDesignBundle:Article")
->findAll();
If I do:
foreach($articles as $article)
{
$steps = $article->getSteps();
I recieve error:
Notice: Undefined index: Steps in /var/www/design/vendor/doctrine/lib/Doctrine/ORM/Persisters/BasicEntityPersister.php line 1280
If I do that:
$articles = $this->getDoctrine()
->getRepository("IftodiDesignBundle:Article")
->findAll();
foreach($articles as $article)
{
//Queries to DB
$steps = $this->getDoctrine()
->getRepository("IftodiDesignBundle:Steps")
->findBy(array(
"article" => $article->getId()
));
$media = $this->getDoctrine()
->getRepository("IftodiDesignBundle:Media")
->findBy(array(
"step" => $steps[0]->getId()
));
I can obtain data that I need, but here are more interrogation to DB.
Delete
@ORM\JoinColumn(name="id", referencedColumnName="id_article")from your annotation – doctrine will map your association into MySQL with sensible defaults.Once you have deleted, regenerate your SQL:
doctrine:schema:update --forceFurthermore if you are looping over your articles to get your steps, you are better off writing a custom method in your repository otherwise each time you call
->getSteps()Doctrine will make an SQL call (imagine looping over 100 articles – you would end up making 101 calls to the database!)To avoid this you can put a method like so in your repository
I put together a few more best practices in a blog post