php - 在 Laravel 和 Eloquent 中获取 2 个以上联接表的数据

标签 php mysql laravel eloquent

这是我的表格。

╔════════════╤═╤══════════╤═╤═══════╗
║ Insurances │ │ Devices  │ │ Brands║
╠════════════╪═╪══════════╪═╪═══════╣
║ id         │ │ id       │ │ id    ║
╟────────────┼─┼──────────┼─┼───────╢
║ IMEI       │ │ type     │ │ name  ║
╟────────────┼─┼──────────┼─┼───────╢
║ device_id  │ │ name     │ │       ║
╟────────────┼─┼──────────┼─┼───────╢
║ user_id    │ │ brand_id │ │       ║
╚════════════╧═╧══════════╧═╧═══════╝

现在我想在表格中显示结果数据

╔══════╤════════════╤═════════════╤══════════════╤═════════╗
║ IMEI │ brand_name │ device_name │ device_price │ user_id ║
╚══════╧════════════╧═════════════╧══════════════╧═════════╝

想象一下,如果是 AJAX,我必须在将数据发送到 View 之前连接表。我已经定义了模型中的关系。但是使用 with() 方法我只能同时调用其中的 2 个,但我不知道如何在 View 中调用它们。

是否有办法不使用普通的DB::class而只使用eloquent?

最佳答案

您应该能够在 Controller 中执行类似的操作,以便在 View 中获得结果。

$insurance = Insurance::with('device.brand')->find($id);

return json_encode([
  'imei' => $insurance->IMEI,
  'brand_name' => $insurance->device~>brand->name,
  'device_name' => $insurance->device->name,
  'device_price' => $insurance->device->price
  'user_id' => $insurance->user_id

]);

关于php - 在 Laravel 和 Eloquent 中获取 2 个以上联接表的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33709206/

相关文章:

sql - Laravel 查询构建器 : left join, 选择,以及不工作的地方

php - 出现异常您的 FFProbe 版本太旧,不支持 `-help` 选项

css - 是否有将 Google 字体添加到 Laravel 元素的最佳实践?

php将数据保存到数组中的数据库中

mysql - SQL查询没有得到正确的支付方式

PHP表单向多个收件人发送电子邮件

php - 使用 fetch_assoc 通过 PHP 遍历 MYSQL 结果

php - 如何在对 SQL 查询进行分组(使用 GROUP BY)后获取行数?

php - 一段时间内多个数组

php - Laravel 多个多对多关系?