Laravel 10,具有3个表格的模型,如何?

huangapple go评论65阅读模式
英文:

Laravel 10, Model with 3 table, how?

问题

如何解决这个问题(Laravel 10),以便我可以通过模型查询来自3个表的所有行和相应的 "instrument_types"?

数据库和模型:
https://i.stack.imgur.com/cuY26.png

我在我的控制器中这样调用它,但显然不好:
$hangszerek = Hangszer::all();

我想要以这样的JSON数据作为响应:

[
  {
    "h_id": 1,
    "hangszer_nev": "Gitár",
    "brutto_ar": 100000,
    "kep_url": "https://image.com/image1.png",
    "cikkszam": "4792146AG",
    "leiras": "Nagyon fain gitár",
    "tipusok":[
      {
        "t_id":1,
        "tipus_nev":"Type 1"
      },
      {
        "t_id":2,
        "tipus_nev":"Type 2"
      }
    ]
  },
  {
    "h_id": 2,
    "hangszer_nev": "Dob",
    "brutto_ar": 120000,
    "kep_url": "https://image.com/image2.png",
    "cikkszam": "47924636BF",
    "leiras": "Nagyon fain dob",
    "tipusok":[
      {
        "t_id":2,
        "tipus_nev":"Type 2"
      },
      {
        "t_id":3,
        "tipus_nev":"Type 3"
      }
    ]
  }
]
英文:

how can I solve it (Laravel 10) so that I can query all the rows and the corresponding "instrument_types" from the 3 tables via a model?

Database and Models:
https://i.stack.imgur.com/cuY26.png

I call it like this in my controller, but it's obviously not good:
$hangszerek = Hangszer::all();

I would like to receive such json data as a response:

  {
    "h_id": 1,
    "hangszer_nev": "Gitár",
    "brutto_ar": 100000,
    "kep_url": "https://image.com/image1.png",
    "cikkszam": "4792146AG",
    "leiras": "Nagyon fain gitár",
    "tipusok":[
      {
      "t_id":1,
      "tipus_nev":"Type 1"
      },
      {
      "t_id":2,
      "tipus_nev":"Type 2"
      }
    ]
  },
  {
    "h_id": 2,
    "hangszer_nev": "Dob",
    "brutto_ar": 120000,
    "kep_url": "https://image.com/image2.png",
    "cikkszam": "47924636BF",
    "leiras": "Nagyon fain dob",
    "tipusok":[
      {
      "t_id":2,
      "tipus_nev":"Type 2"
      },
      {
      "t_id":3,
      "tipus_nev":"Type 3"
      }
    ]
  }
]```




</details>


# 答案1
**得分**: 0

你需要在你的模型之间建立多对多的关系,请阅读[Eloquent:Laravel文档中的关系](https://laravel.com/docs/10.x/eloquent-relationships#many-to-many),然后你应该创建一个Eloquent:API资源来格式化JSON作为响应,请阅读如何在[laravel文档](https://laravel.com/docs/10.x/eloquent-resources#main-content)中执行此操作。

<details>
<summary>英文:</summary>

You need make a relationship many to many between your models read  [Eloquent: Relationships in laravel documentation][1] then you should make an Eloquent: API Resources to format json as response please read how to do it in [laravel documentation][2]


  [1]: https://laravel.com/docs/10.x/eloquent-relationships#many-to-many
  [2]: https://laravel.com/docs/10.x/eloquent-resources#main-content

</details>



huangapple
  • 本文由 发表于 2023年6月15日 03:02:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76476797.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定