Laravel多对多关系 [英] Laravel Many-to-Many Relation
问题描述
我缺少什么? 我有多对多的关系,以确定不返回结果,虽然有相关数据。 / em> MySQL模式: 相关模型: 控制器/视图 / p> 我的问题是 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: Related Models: Controller / View
My issue was that the 这篇关于Laravel多对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
entities
- id
services
- id
entity_service
- entity_id
- service_id
类实体扩展Eloquent实现UserInterface,RemindableInterface
{
// ...
public function services()
{
return $这 - > belongsToMany( '服务');
}
}
class服务扩展Eloquent
{
// ...
public function entities()
{
return $ this-> belongsToMany('Entity');
}
}
$ entity = Entity :: findOrFail($ id);
$ localals ['entity'] = $ entity; //我可以看到所有可用的值
$ locals ['entity_services'] = $ entity-> services(); //我看不到任何值
@foreach($ entity_services as $ service)
{{$ service-> id}}
@endforeach
服务中的code>表是一个独特的
VARCHAR
,而不是标准的自动递增 INT
。修正并添加名称
字段可以解决问题。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
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.