Home > Back-end >  Laravel belongsTo not returning any values
Laravel belongsTo not returning any values

Time:10-01

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);

enter image description here

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

enter image description here

dbc_links table

enter image description here

dbc_link_types table

enter image description here

Any suggestions as to why its returning an empty list?

CodePudding user response:

When invoking the link_type method, Eloquent will attempt to find a DbcLinkType model that has an id which matches the link_type_id column on the DbcLink model.

Eloquent determines the foreign key name by examining the name of the relationship method and suffixing the method name with _id. 1

Rename your relation method from link_type to dbc_link_type so that it looks up dbc_link_type_id column on the DbcLink model.

Alternately, you can inform Eloquent to find the DbcLinkType model that has an id which matches the dbc_link_type_id column on the DbcLink model.

You can accomplish that by specifying the foreignKey when defining the relation;

        return $this->belongsTo(DbcLinkType::class, 'dbc_link_type_id');

CodePudding user response:

You should specify your "Foreign and owner keys" like this:

 public function user()
{
    return $this->belongsTo(TableName::class, 'foreign_key', 'owner_key');
}
  • Related