Reputation: 247
I'm trying to relate two tables on my Laravel 5.x project. One is Banners table and the other is Services table. I can't figure out which Eloquent relation i should use.
On my homepage carousel slider, each of the Banners should represent one of records from the Services table. The only thing i need from Services table is the value of the 'slug' column related to the service.
I thought i can relate two tables by using a 'service_id' column on Banner model pointing to the 'id' column of Service model. Then using that relation to retrieve 'slug' value from Service model.
At first i tried this on Banner model:
public function services() {
return $this->hasMany('App\Service');
}
and retrieve the value using:
$slide->services->slug
but this did not work. Then i tried using 'belongsTo' method instead of 'hasMany'. It did not work either.
I have no idea which eloquent relation and how to use it. I'm open to all suggestions.
Upvotes: 0
Views: 171
Reputation: 247
I solved this by not using Eloquent relations instead using a plain Join statement into query builder.
$banners = DB::table('banners')
->join('services', 'banners.service_id', '=', 'services.id')
->select('banners.*', 'services.slug')
->get();
Upvotes: 0