I have a class called Dbc which has ‘links’ attached to it called DbcLink.
Each link had a ‘type’ (DbcLinkType)
I’m returning the links attached to the Dbc fine
class Dbc extends Model
{
use HasFactory;
public function user()
{
return $this->belongsTo(User::class);
}
public function links($filter = NULL)
{
return $this->hasMany(DBCLink::class);
}
}
$social = $dbc->links()->first();
dd($social);
but when I try and get the ‘link type from those links it returns an empty list
class DbcLink extends Model
{
use HasFactory;
public function dbc()
{
return $this->belongsTo(Dbc::class);
}
public function link_type()
{
return $this->belongsTo(DbcLinkType::class);
}
}
$social = $dbc->links()->first();
dd($social->link_type()->get());
dbc_links table
dbc_link_types table
Any suggestions as to why its returning an empty list?
2
Answers
When invoking the link_type method, Eloquent will attempt to find a
DbcLinkType
model that has anid
which matches thelink_type_id
column on theDbcLink
model.Rename your relation method from
link_type
todbc_link_type
so that it looks updbc_link_type_id
column on theDbcLink
model.Alternately, you can inform Eloquent to find the
DbcLinkType
model that has anid
which matches thedbc_link_type_id
column on theDbcLink
model.You can accomplish that by specifying the foreignKey when defining the relation;
You should specify your "Foreign and owner keys" like this: