【问题标题】:get relations table data is empty获取关系表数据为空
【发布时间】:2022-01-26 16:41:55
【问题描述】:

我正在使用 laravel 8。 我正在尝试获取具有多对多关系的数据,但给我相关表的空数据

这是数据库

订单模式

 public function products()
    {
        return $this->belongsToMany(Product::class);
    }

产品型号

    public function orders(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Order::class);
    }

获取查询是

        $orders = Order::query()->with("products")->get();

结果

我也在检查

        $orders = Order::query()->has("products")->get();

给我同样的结果

【问题讨论】:

  • Order::first()->produts()->dd(); 是否显示您期望的查询? order_product 表中有数据吗?
  • 是的,数据在 order_product 表中可用,我也将两个表的 id 匹配,这很好
  • 您能否检查查询日志以确保没有发生异常情况? DB::enableQueryLog(); $orders = Order::query()->with("products")->get(); dd($orders->toArray(), DB::getQueryLog());
  • @IGP dd(DB::enableQueryLog()); 给我 null 和 dd($orders->toArray()); 给我数组:5 [▼ 0 => 数组:6 [▶] 1 => 数组:6 [▶] 2 => 数组: 6 [▶] 3 => 数组:6 [▶] 4 => 数组:6 [▼ "id" => "0000000017" "status" => 1 "total" => "111" "created_at" => null " updated_at" => null "产品" => [] ] ]
  • 您能否发布ordersorder_productproducts 表中的示例?屏幕截图会很好地显示表格标题。

标签: php laravel relationship


【解决方案1】:

首先,如果您像这样编辑查询,它将起作用

 $orders = Order::fist();
 $orders->products;

为什么?因为数据透视表。

什么是数据透视表?让我解释一下。

当您使用many-to-many 关系时,您必须定义一个中间表,如您的表:order_prodcts。 所以 Laravel 在这里提供了一些非常有用的方式来与这个表交互。

所以这是一个database 结构:

orders:
   - id
   - title

products:
   - id
   - title

order_product:
   - id
   - title

列表中的最终表:order_product 称为pivot

以你的为例

假设我们的Order 模型有很多与之相关的Product 模型。访问此关系后,我们可以使用您在模型上定义的关系方法访问中间表,例如:

1-你的Product 模特

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    //some code

    public function orders()
    {
        return $this->belongsToMany(Product::class);
    }
}

2-你的Order 模特

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    //some code

    public function produtc()
    {
        return $this->belongsToMany(Order::class);
    }
}

这里我们检索到的每个 Product 模型都会自动分配一个关系方法。此关系方法包含一个表示中间order_product 表的模型。

所以在这里尝试用您的产品为您争取订单

public function index()
{

    $orders = Order::get();
    dd($orders->products); //Laravel will handel the pivot and will return your order products
}

现在,在使用 pivot 时有几件事需要提及。

  • 数据透视表字段默认应该只有两个字段:每个表的外键order_idproduct_id

  • 数据透视表的名称应包含 singular 名称

  • 在您的情况下,名称应按alphabetical 顺序排列op 的第一个,因此您的表将被称为order_product

最后感谢您完成阅读我希望您从这个答案中获得任何信息

【讨论】:

  • 我找到了解决方案。由于急切的加载,它是空的。我禁用了急切加载,所以它工作正常......感谢您的帮助
猜你喜欢
  • 2018-01-11
  • 2021-09-22
  • 2021-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多