Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel belongsTo() column naming issue

I can't figure out how to make aliases for my table column names such that I can use Laravel's Eloquent belongsTo() functionality.

I have a groups table and and an activities table. The activities table references the groups table by organization_id rather than groups_id.

How do I write belongsTo in my Activity model as the following doesn't work.

public function group()
{
    return $this->belongsTo('App\Group', 'organization_id');
}

What I'd like to write is:

App\Activity->group 
like image 512
tim peterson Avatar asked Sep 21 '15 18:09

tim peterson


1 Answers

In the code you have pasted laravel will think that the organization id is the column in your activities table which your are using as foreign key what you should do is :

public function group()
{
    return $this->belongsTo('App\Group', 'organization_id', 'id');
}

in the above code you will get all results where activies.id = groups.organization_id;

UPDATE by Tim Peterson

My original code works. I migrated my DB for something else so that must have fixed everything.

like image 148
Khan Shahrukh Avatar answered Nov 15 '22 08:11

Khan Shahrukh