Laravel Many-to-Many Relation

こ雲淡風輕ζ 提交于 2019-12-13 05:07:20

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/21435729/laravel-many-to-many-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!