라이브러리
[PHP] CollectionAdd::execute - 명령문을 실행합니다.
PHP 에서 CollectionAdd::execute는 Doctrine ORM의 기능 중 하나로, Entity에 새로운 데이터를 추가하는 기능입니다.
CollectionAdd::execute 사용법
Doctrine ORM의 CollectionAdd::execute는 Entity의 컬렉션 필드에 새로운 데이터를 추가하는 기능입니다.
# 예제
#hostingforum.kr
php
// Entity
class User
{
/
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
* @ORMManyToMany(targetEntity="Role")
*/
private $roles;
public function __construct()
{
$this->roles = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getRoles(): Collection
{
return $this->roles;
}
public function addRole(Role $role): self
{
if (!$this->roles->contains($role)) {
$this->roles->add($role);
}
return $this;
}
public function removeRole(Role $role): self
{
if ($this->roles->contains($role)) {
$this->roles->removeElement($role);
}
return $this;
}
}
// Role Entity
class Role
{
/
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
* @ORMColumn(type="string", length=255)
*/
private $name;
public function getId(): ?int
{
return $this->id;
}
public function getName(): ?string
{
return $this->name;
}
public function setName(string $name): self
{
$this->name = $name;
return $this;
}
}
// CollectionAdd::execute 사용 예제
$user = new User();
$role1 = new Role();
$role1->setName('ROLE_ADMIN');
$user->addRole($role1);
// CollectionAdd::execute 사용
$entityManager = EntityManager::create($connection, $config);
$entityManager->persist($user);
$entityManager->flush();
// CollectionAdd::execute 사용 후 Role Entity의 데이터 확인
$roleRepository = $entityManager->getRepository(Role::class);
$roles = $roleRepository->findAll();
foreach ($roles as $role) {
echo $role->getName() . "
";
}
CollectionAdd::execute 사용 시 주의점
- Entity의 컬렉션 필드에 새로운 데이터를 추가할 때는 `addRole` 메소드를 사용하여 Entity에 새로운 데이터를 추가해야 합니다.
- `CollectionAdd::execute`를 사용하여 Entity에 새로운 데이터를 추가할 때는 `persist` 메소드를 사용하여 Entity를 영속화해야 합니다.
- `flush` 메소드를 사용하여 Entity를 데이터베이스에 저장해야 합니다.
-
- 나우호스팅 @pcs8404
-
호스팅포럼 화이팅!
댓글목록
등록된 댓글이 없습니다.