はじめに
OneToManyの関係のテーブルにデータを取得(Select)する。
「OneToMany データ追加(Insert)」の続き。
データ取得(Select)
Controllerよりアクセス
ControllerからRepository経由でアクセス
app/Customize/Controller/SamplePageController.php
/**
* @Route("/sample/{id}", name="sample_index")
* @Template("Sample/index.twig")
*/
public function index($id)
{
$product = $this->productRepository->find($id);
dump($product);
$comments = $product->getProductComments();
if (!$comments->isEmpty()) {
dump($comments);
foreach ($comments->toArray() as $comment) {
dump($comment);
}
} else {
}
}
ブラウザよりアクセス
/sample/1 でdtb_productとdtb_product_sizeのデータを取得できた。
Product {#3913 ▼
-_calc: false
-stockFinds: []
-stocks: []
-stockUnlimiteds: []
-price01: []
-price02: []
-price01IncTaxs: []
-price02IncTaxs: []
-codes: []
-classCategories1: []
-classCategories2: []
-className1: null
-className2: null
-id: 1
-name: "彩のジェラートCUBE"
-note: null
-description_list: null
-description_detail: """
冬でも食べたい立方体のジェラート。定番のチョコフレーバーは、チョコレート特有の甘い香りが特徴です。適度な甘みと日本人の口に合いやすいサイズ感で長く愛用いただけます。\n
最高級バニラフレーバーは、贈り物としても人気です。
"""
-search_word: null
-free_area: null
-create_date: DateTime @1538129692 {#3916 ▶}
-update_date: DateTime @1538129692 {#3915 ▶}
-ProductCategories: PersistentCollection {#3952 ▶}
-ProductClasses: PersistentCollection {#3950 ▶}
-ProductImage: PersistentCollection {#4006 ▶}
-ProductTag: PersistentCollection {#4064 ▶}
-CustomerFavoriteProducts: PersistentCollection {#4115 ▶}
-Creator: null
-Status: ProductStatus {#4155 ▶}
-AnnotationReader: AnnotationReader {#263 ▶}
+maker_name: "maker1"
-ProductSize: ProductSize {#4141 ▶}
-ProductComments: PersistentCollection {#4145 ▼
-snapshot: []
-owner: Product {#3913}
-association: array:15 [ …15]
-em: EntityManager {#655 …11}
-backRefFieldName: "Product"
-typeClass: ClassMetadata {#3623 …}
-isDirty: false
#collection: ArrayCollection {#4147 ▼
-elements: []
}
#initialized: false
}
}
PersistentCollection {#4145 ▼
-snapshot: array:2 [ …2]
-owner: Product {#3913 ▶}
-association: array:15 [ …15]
-em: EntityManager {#655 …11}
-backRefFieldName: "Product"
-typeClass: ClassMetadata {#3623 …}
-isDirty: false
#collection: ArrayCollection {#4147 ▼
-elements: array:2 [▼
0 => ProductComment {#4212 ▼
-id: 1
-product_id: 1
-comment: """
=2019/01/08 12:17:58\n
productId1\n
==1==
"""
-create_date: DateTime @1546917478 {#4209 ▶}
-update_date: DateTime @1546917478 {#4210 ▶}
-Product: Product {#3913 ▶}
-AnnotationReader: AnnotationReader {#263 ▶}
}
1 => ProductComment {#4216 ▼
-id: 2
-product_id: 1
-comment: """
=2019/01/08 12:17:58\r\n
productId1\r\n
==2==
"""
-create_date: DateTime @1546917478 {#4214 ▶}
-update_date: DateTime @1546917478 {#4215 ▶}
-Product: Product {#3913 ▶}
-AnnotationReader: AnnotationReader {#263 ▶}
}
]
}
#initialized: true
}
まとめ
親をfind()して子オブジェクトを参照。
実際に子要素を取得するのは $product->getProductComments()
したときか。