Laravel多对多关系

编程入门 行业动态 更新时间:2024-10-27 21:22:22
本文介绍了Laravel多对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我缺少什么?

我有多对多的关系,以确定不返回结果,虽然有相关数据。 / em>

MySQL模式:

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

控制器/视图 / p>

$ entity = Entity :: findOrFail($ id); $ localals ['entity'] = $ entity; //我可以看到所有可用的值 $ locals ['entity_services'] = $ entity-> services(); //我看不到任何值 @foreach($ entity_services as $ service) {{$ service-> id}} @endforeach

解决方案

我的问题是 服务中的code>表是一个独特的 VARCHAR ,而不是标准的自动递增 INT 。修正并添加名称字段可以解决问题。

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

解决方案

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.

更多推荐

Laravel多对多关系

本文发布于:2023-10-23 13:29:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520954.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:关系   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!