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()):

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

$chairb = new Chair(); echo $chairb->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;