user3641381
user3641381

Reputation: 1076

laravel relation returning null

The following keeps bothering me.

UPDATE

I, firstly, posted a code which was not meant to post. I updated the code. Please take a look.

A table called plates

 $table->increments('id');
 $table->integer('equipment_status_code_id')->unsigned();
 $table->foreign('equipment_status_code_id')->references('id')->on('equipment_status_codes')->onDelete('cascade')->onUpdate('cascade');

And model plates

public function equipmentStatusCode()
{
   return $this->belongsTo('App\Models\EquipmentStatusCode');
}

and EquipmentStatusCode

   public function plate()
    {
         return $this->hasOne('App\Models\Plate');
    }

In route I do this

   $data = Plate::find(1);
   $att = $data->equipmentStatusCode;

   dd($att);

And works just fine.

But the other way around won't work and returns null

$data = EquipmentStatusCode::find(1);
$att = $data->plate;

dd($att);

Someone tells me what's going on?

Upvotes: 0

Views: 81

Answers (1)

Andy Noelker
Andy Noelker

Reputation: 11269

The model with the BelongsTo relation should have the foreign key in its table. You have it the other way around. So just swap the relations.

Plate Model:

public function equipmentStatusCode()
{
   return $this->hasOne('App\Models\EquipmentStatusCode');
}

EquipmentStatusCode Model:

public function plate()
{
   return $this->belongsTo('App\Models\Plate');
} 

Upvotes: 1

Related Questions