0

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?

1 Answer 1

1

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');
} 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.