facebook twitter hatena line google mixi email

Php/Symfony/Symfony2/doctrine/リレーション

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

リレーション準備

カテゴリテーブルを作る

php app/console doctrine:generate:entity --entity="AcmeHelloBundle:Category" --fields="name:string(255)"
CREATE TABLE `categorys` (
 `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 categorys(id, name) values(1, "1組");
INSERT INTO categorys(id, name) values(2, "2組");
select * from categorys;
+----+------+
| id | name |
+----+------+
|  1 | 1組  |
|  2 | 2組  |

リレーションをクラスに定義

Entity/User.phpに以下を追加

namespace Acme\HelloBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
 * User
 *
 * @ORM\Table()
 * @ORM\Entity
 */
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に以下を追加

namespace Acme\HelloBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
/**
 * Category
 *
 * @ORM\Table()
 * @ORM\Entity
 */
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 users;

 CREATE TABLE `users` (
 `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 `categorys` (`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();
}
// selectが2つ実行される
// doctrine.DEBUG: SELECT t0.id AS id1, t0.name AS name2, t0.description AS description3, t0.category_id AS category_id4 FROM users t0 WHERE t0.id = ? [6] []
// doctrine.DEBUG: SELECT t0.id AS id1, t0.name AS name2 FROM categorys t0 WHERE t0.id = ? [1] []

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();
   }
}
// selectが2つ実行される
doctrine.DEBUG: SELECT t0.id AS id1, t0.name AS name2 FROM categorys t0 WHERE t0.id = ? [1] []
doctrine.DEBUG: SELECT t0.id AS id1, t0.name AS name2, t0.description AS description3, t0.category_id AS category_id4 FROM users t0 WHERE t0.category_id = ? [1] []