Php/Symfony/Symfony2/doctrine/リレーション
リレーション準備
カテゴリテーブルを作る
php app/console doctrine:generate:entity --entity="AcmeHelloBundle:Category" --fields="name:string(255)"
CREATE TABLE `Category` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
INSERT INTO Category(id, name) values(1, "1組"); INSERT INTO Category(id, name) values(2, "2組"); select * from Category; +----+------+ | id | name | +----+------+ | 1 | 1組 | | 2 | 2組 |
リレーションをクラスに定義
Entity/User.phpに以下を追加
class User
{
/**
* @ORM\ManyToOne(targetEntity="Category", inversedBy="users")
* @ORM\JoinColumn(name="category_id", referencedColumnName="id")
*/
protected $category;
public function getCategory()
{
return $this->category;
}
Entity/Category.phpに以下を追加
class Category
{
/**
* @ORM\OneToMany(targetEntity="User", mappedBy="category")
*/
protected $users;
public function __construct()
{
$this->users = new ArrayCollection();
}
public function getUsers()
{
return $this->users;
}
dbに外部キーを反映する
$ php app/console doctrine:schema:update --force
show create table user;
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `description` longtext COLLATE utf8_unicode_ci NOT NULL, `category_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `IDX_2DA1797712469DE2` (`category_id`), CONSTRAINT `FK_2DA1797712469DE2` FOREIGN KEY (`category_id`) REFERENCES `Category` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
リレーションデータをselectする
カテゴリ付きuserを取得
$repository = $this->getDoctrine()
->getRepository('AcmeHelloBundle:User');
$user = $repository->find(6);
if ($user) {
echo $user->getId();
echo $user->getName();
echo $user->getCategory()->getName();
}
userリスト付きカテゴリ
$repository = $this->getDoctrine()
->getRepository('AcmeHelloBundle:Category');
$category = $repository->find(1);
if ($category) {
echo $category->getId();
echo $category->getName();
foreach ($category->getUsers() as $user) {
echo $user->getName();
}
}