Reputation: 6351
I have a many-to-many relationship to establish that is not returning results, although there is relevant data.
What am I missing?
MySQL Schema:
entities
- id
services
- id
entity_service
- entity_id
- service_id
Related Models:
class Entity extends Eloquent implements UserInterface, RemindableInterface
{
// ...
public function services()
{
return $this->belongsToMany('Service');
}
}
class Service extends Eloquent
{
// ...
public function entities()
{
return $this->belongsToMany('Entity');
}
}
Controller / View
$entity = Entity::findOrFail($id);
$locals['entity'] = $entity; // I can see all values available here
$locals['entity_services'] = $entity->services(); // I can't see any values here
@foreach ($entity_services as $service)
{{$service->id}}
@endforeach
Upvotes: 0
Views: 300
Reputation: 6351
My issue was that the id
in the services
table was an unique VARCHAR
instead of the standard auto-incrementing INT
. Fixing that and adding a name
field cleared up the issue.
Upvotes: 0
Reputation: 3658
Laravel makes certain assumptions about your pivot table based on the model names. It doesn't always get it right, and I suspect that's the case with "entities" and "entity_service." Specify the pivot table and keys manually:
class Entity extends Eloquent implements UserInterface, RemindableInterface
{
// ...
public function services()
{
return $this->belongsToMany('Service', 'entity_service', 'entity_id', 'service_id');
}
}
class Service extends Eloquent
{
// ...
public function entities()
{
return $this->belongsToMany('Entity', 'entity_service', 'entity_id', 'service_id');
}
}
Try eager loading the data:
Entity::with('services')->get();
The Laravel docs cover this in detail @ http://laravel.com/docs/eloquent#relationships.
Upvotes: 1