Tôi phải kiểm tra xem thực thể Email
đã tồn tại trong ArrayCollection
hay chưa. Tôi phải thực hiện kiểm tra email dưới dạng chuỗi (thực thể chứa ID và một số mối quan hệ với các đơn vị khác) vì lý do này tôi sử dụng một bảng riêng biệt mà vẫn tồn tại tất cả các email).Cách sử dụng ArrayCollection của Doctrine :: Phương thức tồn tại
Bây giờ, trong lần đầu tiên tôi đã viết mã này:
/**
* A new Email is adding: check if it already exists.
*
* In a normal scenario we should use $this->emails->contains().
* But it is possible the email comes from the setPrimaryEmail method.
* In this case, the object is created from scratch and so it is possible it contains a string email that is
* already present but that is not recognizable as the Email object that contains it is created from scratch.
*
* So we hav to compare Email by Email the string value to check if it already exists: if it exists, then we use
* the already present Email object, instead we can persist the new one securely.
*
* @var Email $existentEmail
*/
foreach ($this->emails as $existentEmail) {
if ($existentEmail->getEmail()->getEmail() === $email->getEmail()) {
// If the two email compared as strings are equals, set the passed email as the already existent one.
$email = $existentEmail;
}
}
Nhưng đọc lớp ArrayCollection
Tôi thấy phương pháp exists
điều đó dường như là một cách elgant hơn để làm điều tương tự tôi đã làm.
Nhưng tôi không biết cách sử dụng: ai đó có thể giải thích cho tôi cách sử dụng phương pháp này cho mã ở trên không?
hi @Aerendir tốt công việc! – Matteo