Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

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 /


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;