Skip to content

Commit

Permalink
Added code to make loading data for hasOne & belongsTo relationships …
Browse files Browse the repository at this point in the history
…to be set to an empty array when there's no matching relational data.
  • Loading branch information
rotimi committed Nov 27, 2024
1 parent 52a23fd commit 5de9dd6
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/LeanOrm/DBConnector.php
Original file line number Diff line number Diff line change
Expand Up @@ -306,7 +306,7 @@ public function getConnectionName(): string {
*
* @return mixed result of the query or false on failure or if there are no rows
*/
public function dbFetchOne(string $select_query, array $parameters = [] ) {
public function dbFetchOne(string $select_query, array $parameters = [] ): mixed {

$result = static::_execute($select_query, $parameters, true, $this->connection_name);
/** @psalm-suppress PossiblyInvalidArrayAccess */
Expand Down
16 changes: 13 additions & 3 deletions src/LeanOrm/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -1017,7 +1017,11 @@ protected function loadHasOne(
* @psalm-suppress MixedArrayOffset
* @psalm-suppress MixedMethodCall
*/
$parent_data[$p_rec_key]->setRelatedData($rel_name, $matching_related_rows[0]);
$parent_data[$p_rec_key]->setRelatedData(
$rel_name,
(\count($matching_related_rows) > 0)
? $matching_related_rows[0] : []
);

} else {

Expand All @@ -1031,8 +1035,11 @@ protected function loadHasOne(
* @psalm-suppress MixedArrayOffset
* @psalm-suppress MixedArrayAssignment
* @psalm-suppress MixedArgument
* @psalm-suppress PossiblyInvalidArgument
*/
$parent_data[$p_rec_key][$rel_name] = $matching_related_rows[0];
$parent_data[$p_rec_key][$rel_name] =
(\count($matching_related_rows) > 0)
? $matching_related_rows[0] : [];
}
} // foreach( $parent_data as $p_rec_key => $parent_record )

Expand All @@ -1050,7 +1057,10 @@ protected function loadHasOne(

//stitch the related data to the parent record
/** @psalm-suppress MixedArgument */
$parent_data->setRelatedData($rel_name, array_shift($related_data));
$parent_data->setRelatedData(
$rel_name,
(\count($related_data) > 0) ? \array_shift($related_data) : []
);
} // else if ($parent_data instanceof \GDAO\Model\RecordInterface)
} // if( array_key_exists($rel_name, $this->relations) )
}
Expand Down

0 comments on commit 5de9dd6

Please sign in to comment.