OneToOne データ追加(Insert)

# はじめに
OneToOneの関係のテーブルにデータを追加(Insert)する。
dtb_product_sizeというテーブルを作成し、dtb_productとproduct_idでOneToOneする。

# Entity作成～テーブル作成
## dtb_product_sizeテーブル作成
dtb_product_sizeは以下のイメージ

```sql
CREATE TABLE `dtb_product_size` (
  `id` int(10) UNSIGNED NOT NULL,
  `product_id` int(10) UNSIGNED NOT NULL,
  `size_a` int(10) UNSIGNED NOT NULL,
  `size_b` int(10) UNSIGNED NOT NULL,
  `create_date` datetime NOT NULL COMMENT '(DC2Type:datetimetz)',
  `update_date` datetime NOT NULL COMMENT '(DC2Type:datetimetz)',
  `discriminator_type` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;```

## Entity(1)

```php:app/Customize/Entity/ProductSize.php
<?php

namespace Customize\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;


/**
 * ProductSize
 *
 * @ORM\Table(name="dtb_product_size")
 * @ORM\InheritanceType("SINGLE_TABLE")
 * @ORM\DiscriminatorColumn(name="discriminator_type", type="string", length=255)
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Entity(repositoryClass="Customize\Repository\ProductSizeRepository")
 */
class ProductSize extends \Eccube\Entity\AbstractEntity
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", options={"unsigned":true})
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="product_id", type="integer", options={"unsigned":true})
     */
    private $product_id;

    /**
     * @var integer
     *
     * @ORM\Column(name="size_a", type="integer", options={"unsigned":true})
     */
    private $size_a;

    /**
     * @var integer
     *
     * @ORM\Column(name="size_b", type="integer", options={"unsigned":true})
     */
    private $size_b;

    /**
     * @return string
     */
    public function __toString()
    {
        return sprintf("[%d] a:%d b:%d", $this->getProductId(), $this->getSizeA(), $this->getSizeB());
    }

    /**
     * Get id.
     *
     * @return int
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set productId.
     *
     * @param int|null $productId
     *
     * @return ProductSize
     */
    public function setProductId($productId = null)
    {
        $this->product_id = $productId;

        return $this;
    }

    /**
     * Get productId.
     *
     * @return int|null
     */
    public function getProductId()
    {
        return $this->product_id;
    }

    /**
     * Set sizeA.
     *
     * @param int|null $sizeA
     *
     * @return ProductSize
     */
    public function setSizeA($sizeA = null)
    {
        $this->size_a = $sizeA;

        return $this;
    }

    /**
     * Get sizeA.
     *
     * @return int|null
     */
    public function getSizeA()
    {
        return $this->size_a;
    }

    /**
     * Set sizeB.
     *
     * @param int|null $sizeB
     *
     * @return ProductSize
     */
    public function setSizeB($sizeB = null)
    {
        $this->size_b = $sizeB;

        return $this;
    }

    /**
     * Get sizeB.
     *
     * @return int|null
     */
    public function getSizeB()
    {
        return $this->size_b;
    }

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="create_date", type="datetimetz")
     */
    private $create_date;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="update_date", type="datetimetz")
     */
    private $update_date;

    /**
     * Set createDate.
     *
     * @param \DateTime $createDate
     *
     * @return Product
     */
    public function setCreateDate($createDate)
    {
        $this->create_date = $createDate;

        return $this;
    }

    /**
     * Get createDate.
     *
     * @return \DateTime
     */
    public function getCreateDate()
    {
        return $this->create_date;
    }

    /**
     * Set updateDate.
     *
     * @param \DateTime $updateDate
     *
     * @return Product
     */
    public function setUpdateDate($updateDate)
    {
        $this->update_date = $updateDate;

        return $this;
    }

    /**
     * Get updateDate.
     *
     * @return \DateTime
     */
    public function getUpdateDate()
    {
        return $this->update_date;
    }

    /**
     * @var \Eccube\Entity\Product
     *
     * @ORM\OneToOne(targetEntity="Eccube\Entity\Product", inversedBy="ProductSize")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     * })
     */
    private $Product;

    /**
     * Set product.
     *
     * @param \Eccube\Entity\Product|null $product
     *
     * @return ProductSize
     */
    public function setProduct(\Eccube\Entity\Product $product = null)
    {
        $this->Product = $product;

        return $this;
    }

    /**
     * Get product.
     *
     * @return \Eccube\Entity\Product|null
     */
    public function getProduct()
    {
        return $this->Product;
    }
}
```

## Repository

```php:app/Customize/Repository/ProductSizeRepository.php
<?php

namespace Customize\Repository;

use Customize\Entity\ProductSize;
use Eccube\Repository\AbstractRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;

/**
 * ProductSizeRepository
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ProductSizeRepository extends AbstractRepository
{
    public function __construct(RegistryInterface $registry)
    {
        parent::__construct($registry, ProductSize::class);
    }
}
```

## Entity(2)

```php:app/Customize/Entity/ProductTrait.php
<?php

namespace Customize\Entity;

use Doctrine\ORM\Mapping as ORM;
use Eccube\Annotation\EntityExtension;

/**
  * @EntityExtension("Eccube\Entity\Product")
 */
trait ProductTrait
{
    /**
     * @ORM\Column(type="string", nullable=true)
     */
    public $maker_name;

    /**
     * Set maker_name.
     *
     * @param string $maker_name
     *
     * @return Product
     */
    public function setMakerName($maker_name)
    {
        $this->maker_name = $maker_name;

        return $this;
    }

    /**
     * Get maker_name.
     *
     * @return string
     */
    public function getMakerName()
    {
        return $this->maker_name;
    }

    /**
     * @var \Customize\Entity\ProductSize
     *
     * @ORM\OneToOne(targetEntity="Customize\Entity\ProductSize", mappedBy="Product", cascade={"persist","remove"})
     */
    private $ProductSize;

    /**
     * Set productSize.
     *
     * @param \Customize\Entity\ProductSize|null $productSize
     *
     * @return Product
     */
    public function setProductSize(\Customize\Entity\ProductSize $productSize = null)
    {
        $this->ProductSize = $productSize;

        return $this;
    }

    /**
     * Get productSize.
     *
     * @return \Customize\Entity\ProductSize|null
     */
    public function getProductSize()
    {
        return $this->ProductSize;
    }

}
```

## mappedBy/inversedBy
dtb_productが親テーブルでdtb_product_sizeが子テーブル

親エンティティでmappedBy→子エンティティで指定する自分

```php:app/Customize/Entity/ProductSize.php
/**
 * @var \Customize\Entity\ProductSize
 *
 * @ORM\OneToOne(targetEntity="Customize\Entity\ProductSize", mappedBy="Product", cascade={"persist","remove"})
 */
private $ProductSize;
```

子エンティティでinversedBy→親エンティティで指定する自分

```php:app/Customize/Entity/ProductTrait.php
/**
 * @var \Eccube\Entity\Product
 *
 * @ORM\OneToOne(targetEntity="Eccube\Entity\Product", inversedBy="ProductSize")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="product_id", referencedColumnName="id")
 * })
 */
private $Product;
```

## テーブル作成
doctrine機能を利用してテーブル作成
(自動で外部キーとかも設定してくれるので)

```sh
php bin/console cache:clear --no-warmup
php bin/console eccube:generate:proxies #dtb_product用proxyを作成していない場合
php bin/console doctrine:schema:update --dump-sql
php bin/console doctrine:schema:update --dump-sql --force
```

作成結果

```sql
CREATE TABLE `dtb_product_size` (
  `id` int(10) UNSIGNED NOT NULL,
  `product_id` int(10) UNSIGNED NOT NULL,
  `size_a` int(10) UNSIGNED NOT NULL,
  `size_b` int(10) UNSIGNED NOT NULL,
  `create_date` datetime NOT NULL COMMENT '(DC2Type:datetimetz)',
  `update_date` datetime NOT NULL COMMENT '(DC2Type:datetimetz)',
  `discriminator_type` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
ALTER TABLE `dtb_product_size`
  ADD PRIMARY KEY (`id`),
  ADD KEY `IDX_CF5F5CFE4584665A` (`product_id`);
ALTER TABLE `dtb_product_size`
  MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
ALTER TABLE `dtb_product_size`
  ADD CONSTRAINT `FK_CF5F5CFE4584665A` FOREIGN KEY (`product_id`) REFERENCES `dtb_product` (`id`);
```

# データ追加(Insert)
## Controllerよりアクセス
ControllerからentityManager経由でアクセス

```php:app/Customize/Controller/SamplePageController.php
/**
 * @Route("/sample/{id}", name="sample_index")
 * @Template("Sample/index.twig")
 */
public function index($id)
{
    $product = new Product();
    $product_size = new ProductSize();
    $product_size->setSizeA(300)->setSizeB(400)->setProduct($product);
    $product->setName('サンプル３')->setProductSize($product_size);
    $this->entityManager->persist($product);
    $this->entityManager->flush();
    log_info("productId", [$product->getId(),$product_size->getId(),$product_size->getProductId()]);

    $product = $this->productRepository->find($id);
    $productSize = $this->productSizeRepository->find($id);
    // $product2 = $product->getProduct2();

    return [
        'shop_name' => $this->baseInfo->getShopName(),
        // 'maker_name' => $product->maker_name,
        'maker_name' => $product->getMakerName(),
        'product_name' => $product->getName(),
        'size_a' => $productSize->getSizeA(),
        // 'size_a' => "10",
    ];
}
```


## ブラウザよりアクセス
/sample/1 でdtb_productとdtb_product_sizeにデータ追加(Insert)された。

```
INSERT INTO dtb_product (name, note, description_list, description_detail, search_word, free_area, create_date, update_date, maker_name, creator_id, product_status_id, discriminator_type) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Parameters:

[▼
  1 => "サンプル３"
  2 => null
  3 => null
  4 => null
  5 => null
  6 => null
  7 => "2018-12-27 01:32:12"
  8 => "2018-12-27 01:32:12"
  9 => null
  10 => null
  11 => null
  12 => "product"
]

INSERT INTO dtb_product_size (product_id, size_a, size_b, create_date, update_date, discriminator_type) VALUES (?, ?, ?, ?, ?, ?)

Parameters:

[▼
  1 => 3
  2 => 300
  3 => 400
  4 => "2018-12-27 01:32:12"
  5 => "2018-12-27 01:32:12"
  6 => "productsize"
]
```

```sql
INSERT INTO `dtb_product` (`id`, `creator_id`, `product_status_id`, `name`, `note`, `description_list`, `description_detail`, `search_word`, `free_area`, `create_date`, `update_date`, `discriminator_type`, `maker_name`) VALUES
(3, NULL, NULL, 'サンプル３', NULL, NULL, NULL, NULL, NULL, '2018-12-27 01:32:12', '2018-12-27 01:32:12', 'product', NULL);
INSERT INTO `dtb_product_size` (`id`, `product_id`, `size_a`, `size_b`, `create_date`, `update_date`, `discriminator_type`) VALUES
(3, 3, 300, 400, '2018-12-27 01:32:12', '2018-12-27 01:32:12', 'productsize');
```

#まとめ
EntityのmappedBy/inversedByでそれぞれ相手オブジェクトを指定してpersist()/flush()する。

#参照
[Symfony2 Doctrine2の小ネタ(OneToOneリレーション)](https://www.skyarch.net/blog/?p=2510)