Charlie Brown
Charlie Brown

Reputation: 2825

Symfony 2.0 Model relationships

I am trying to model the following table structure in Symfony 2.0 using annotations.

   State
PK Code
   Name

   County
PK State_Code -> FK State.Code
PK Code
   Name

   Muni
PK State_Code -> FK.State.Code
PK County_Code -> FK County.Code
PK Code
   Name

Modeling the fields and the state - county relationship is simple enough, but I cannot determine how to define the relationship for the Muni table.

The table structure is legacy and cannot be modified.

Upvotes: 0

Views: 321

Answers (1)

Ondrej Slinták
Ondrej Slinták

Reputation: 31910

Here you go. Tested with Symfony 2.0.5 (Doctrine 2.1):

State.php

namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * State
 *
 * @ORM\Entity
 */
class State
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\OneToMany(targetEntity="County", mappedBy="state_code")
     */
    private $counties;

    /**
     * @ORM\OneToMany(targetEntity="Muni", mappedBy="state_code")
     */
    private $munis;
}

County.php

namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * County
 *
 * @ORM\Entity()
 */
class County
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="State", inversedBy="counties")
     * @ORM\JoinColumn(name="State_Code", referencedColumnName="Code")
     */
    private $state_code;

    /**
     * @ORM\OneToMany(targetEntity="Muni", mappedBy="county_code")
     */
    private $munis;
}

Muni.php

namespace Acme\WhateverBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Muni
 *
 * @ORM\Entity
 */
class Muni
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\Column(name="Code", type="integer")
     */
    private $code;

    /**
     * @ORM\Column(name="Name", type="string")
     */
    private $name;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="County", inversedBy="munis")
     * @ORM\JoinColumn(name="County_Code", referencedColumnName="Code")
     */
    private $county_code;

    /**
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     * @ORM\ManyToOne(targetEntity="State", inversedBy="munis")
     * @ORM\JoinColumn(name="State_Code", referencedColumnName="Code")
     */
    private $state_code;
}

Don't forget to generate getters/setters. All relationships are bi-directional.

Upvotes: 2

Related Questions