We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

How to handle uncertain Models relations ?

Hi guys.

I have a model Chair and another one Table. Table has many Chair. Chair has one *OR NONE Table.

How can i deal in this situation without havinf to test if($chair_b->getTable()):

$chair_a = Chair::findFirstById(4330); echo $chair_a->getTable()->getId(); / Outputs int 660 /

$chair_b = new Chair(); echo $chair_b->getTable()->getId() / This will output an error /



11.2k
Accepted
answer

Inside your Chair model you could create a function called getRelatedTableIdOrNull and it would be something like

public function getRelatedTableIdOrNull()
{
    $table = $this->getTable();
    if ($table) {
        return $table->getId();
    }
    return null;
}