dai007uk dai007uk - 7 months ago 11
SQL Question

Laravel Model/View Relationship

I am learning Laravel and just can't understand how to solve the below issue.

I have two tables (ofcourse not databases) :)

Table: Birds
id
name
species
....

Table: Eggs
id
egg_number
parent_id
....


Sample Data:

bird
id 1
name Jeff

egg
id 1
parent_id 1


I have two models which are Bird and Egg
I am simply displaying the data which is available in the database (MySQL).

eggs.blade.php

@foreach ($eggs as $egg)
..form data
{{ $egg->id }}
{{ $egg->parent_id }}
..end of form
@endforeach


This works all fine. However I wish to show the name of the parent (bird) instead of the id. (so from the sample data it will show Jeff)

I have tried using this in the models

return $this->belongsTo('Bird'); //in Egg Model
return $this->belongsTo('Egg'); //in Bird Model


Would be really grateful for any help/explanation regarding this.

Answer

In your Egg model you need to setup the relationship like so:

public function bird()
{
    return $this->belongsTo(Bird::class,'parent_id');
}

If your column would have been bird_id it would have found the foreign key column on it's own however since it automatically tries the model name appended with _id it doesn't know which column to use. But you can directly specify the column that references the primary key of Bird with the second parameter in belongsTo().

Once you do this you will simply be able to reference the relationship like so:

{{ $egg->bird->name }}
Comments