我在管理我的关系时遇到问题(仅在mysql中,大声笑!;))
MySQL方案:
一个属性可以具有多个值。例如: 属性ID 1 =>值ID 1,值ID 4 属性ID 2 =>值ID 1,值ID 3,值ID 2
sql:
CREATE TABLE `property_values` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`value_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
`value_img` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`property_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_44D0239A549213EC` (`property_id`),
CONSTRAINT `FK_44D0239A549213EC` FOREIGN KEY (`property_id`) REFERENCES `property` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `property` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
`description` longtext COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
我做了什么?
php bin/console make:entity
并在用户实体OneToMany中创建了现实: Property.php
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\OneToMany(targetEntity="App\Entity\PropertyValues", mappedBy="property")
*/
private $propertyValue;
public function __construct()
{
$this->propertyValue = new ArrayCollection();
}
/**
* @return Collection|PropertyValues[]
*/
public function getPropertyValue(): Collection
{
return $this->propertyValue;
}
和 PropertyValues.php
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Property", inversedBy="propertyValue")
*/
private $property;
public function getProperty(): ?Property
{
return $this->property;
}
public function setProperty(?Property $property): self
{
$this->property = $property;
return $this;
}
在我的控制器文件中,我需要创建表,所以我要这样做:
$property = $this->getDoctrine()
->getRepository(Property::class)
->find($id);
if (!$property) {
throw $this->createNotFoundException(
'404:' . $id;
);
}
return $this->render('home/index.html.twig', [
'controller_name' => 'HomeController',
'property' => $property
]);
但是当我试图通过以下方式在我的树枝模板中转储属性var时:
{{dump(property}}
我得到了属性数据,但是没有来自PropertyElements的任何元素:
-propertyValue: PersistentCollection^ {#834 ▼
-snapshot: []
-owner: Property^ {#770}
-association: array:15 [ …15]
-em: EntityManager^ {#522 …11}
-backRefFieldName: "property"
-typeClass: ClassMetadata {#772 …}
-isDirty: false
#collection: ArrayCollection^ {#741 ▼
-elements: []
}
属性值表信息:
KEY `IDX_44D0239A549213EC` (`property_id`),
CONSTRAINT `FK_44D0239A549213EC` FOREIGN KEY (`property_id`)
REFERENCES `property` (`id`)) ENGINE=InnoDB AUTO_INCREMENT=7
DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
这是我与ORM的第一次接触。我试图从几个小时开始这样做。在mysql中,我只是使用“ JOIN”查询,并且一切正常:)
如何从加入PropertyValues的Property中选择所有数据?
感谢您的帮助!
schema:validate :
Mapping
-------
[OK] The mapping files are correct.
Database
-------
[OK] The database schema is in sync with the mapping files.
[OK] Nothing to update - your database is already in sync with the current entity metadata.