Laravel多对多关系

时间:2014-01-29 15:40:39

标签: php laravel-4 eloquent

虽然存在相关数据,但我建立的多对多关系不会返回结果。

我缺少什么?

MySQL架构:

entities
    - id

services
    - id

entity_service
    - entity_id
    - service_id

相关型号:

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');
    }
}

控制器/视图

$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

2 个答案:

答案 0 :(得分:1)

Laravel根据模型名称对您的数据透视表做出某些假设。它并不总是正确的,我怀疑是“实体”和“entity_service”的情况。手动指定数据透视表和密钥:

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');
    }
}

尝试急切加载数据:

Entity::with('services')->get();

Laravel文档详细介绍了@ http://laravel.com/docs/eloquent#relationships

答案 1 :(得分:0)

我的问题是id表中的services是唯一的VARCHAR,而不是标准的自动递增INT。修复此问题并添加name字段可以解决问题。