kevinabraham kevinabraham - 2 months ago 11
MySQL Question

How to get one->many relationship with a foreign key in laravel 5.2?

I am using laravel 5.2. My Database is set up as:

social_logins
ID | social_id | provider
-----------------------------
1 | x | twitter
2 | y | facebook
3 | z | twitter

twitter_data
ID | social_id | some_value
-------------------------------
1 | x | 100
2 | y | 200
3 | z | 100


My relationship for the social_logins model is set up as:

public function twitterData()
{
return $this->hasMany('App\Models\TwitterData', 'social_id');
}


I want to retrieve back the all the twitter data with the foreign key of social_id in the table. So far I've tried:

$socialLogin = Social::find($id);
dd($socialLogin->twitterCounts);


but when I try this I just get an empty collection

Collection {#346 ▼
#items: []
}


How do I retrieve the one to many relationship with the foreign key in laravel 5.2?

Please note when I do this manually with something like this:

TwitterData::where('social_id', $socialLogin->social_id)->get();


It returns back all the data correctly.

Answer

Add local key to your relation method:

public function twitterData()
    {
        return $this->hasMany('App\Models\TwitterData', 'social_id','social_id');
    }