Hi I need to compare two objects in doctrine. I have customer repository and entity. This is my code,
public function index(CarAdRepository $carAdRepository, CustomerRepository $customerRepository): Response {
$cus = $customerRepository->findAll();
$customer = new Customer();
$customer->setTitle('Mr');
$customer->setName('aaa');
$customer->setLastName('bbb');
if($customer == $cus[0]){
echo 'ddd';
}else{
echo 'no';
}
}
in my table I have this values,

But I always get no. It would be great if someone can help
Doctrine implements IdentityMap pattern that ensures that you're always receiving same object for same database row, but only if it was loaded from identity map.
In your case you're comparing some arbitrary object with entity fetched from database using PHP comparison operator. In other words you're checking if 2 objects are equal, but there is no such built-in functionality in PHP.
You have to implement objects comparison function by yourself to achieve your goal because actual comparison logic may vary.
UPDATE: Simplest example of comparison in your case is property-by-property comparison:
private function compare(Customer $a, Customer $b)
{
return $a->getTitle() === $b->getTitle() &&
$a->getName() === $b->getName() &&
$a->getLastName() === $b->getLastName();
}
It also may be worth to move this method directly into Customer entity with name like isEqual().
It is also possible to implement more generic approach by using reflection, but it may bring certain level of complexity in a case if some non-trivial comparison will need to be involved.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With