简体   繁体   中英

Laravel Many-to-Many Relation

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

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM