Reputation: 109
I am pulling data from my database on specific entity and form other tables related to them.
How can I skip an error when some object is null in db?
Error is:
Call to a member function getName() on null
Code:
$results = $this->getMyRepository()->findAll();
$rows = [];
$rows[] = array(
"id",
"user",
"category"
);
foreach ($results as $row) {
$rows[] = [
$row->getId(),
$row->getUser()->getFullName(),
$row->getCategory()->getName(),
];
}
return $rows;
}
Upvotes: 1
Views: 245
Reputation: 488
This is not an error, but exception. Errors might be suppressed by "@" operator.
You can't just skip exception. To handle them you need to use try-catch block.
Perhaps you want to check if user and category exists. Your code might look like this below (using ternary operator).
foreach ($results as $row) {
$rows[] = [
$row->getId(),
($user = $row->getUser()) ? $user->getFullName() : null,
($category = $row->getCategory()) ? $category->getName() : null,
];
}
Upvotes: 2
Reputation: 1424
You can simply check if the variable is null before working with it
foreach ($results as $row) {
$rows[] = [
$row->getId(),
$row->getUser()->getFullName(),
!is_null($row->getCategory()->getName()) ? $row->getCategory()->getName() : '',
];
}
Documentation: is_null
Upvotes: 1