我在急切加载中遇到问题-PHP laravel

时间:2018-07-10 13:28:35

标签: php mysql laravel orm eager-loading

当我从模型中获取数据时,我渴望加载,我渴望加载3关系,要理解这里的问题是我从模型中获取模型时的迁移

$table->increments('id'); $table->unsignedInteger('order_id'); $table->unsignedInteger('product_item_id'); $table->unsignedInteger('product_id'); $table->integer('days'); $table->foreign('order_id')

        ->references('id')

        ->on('orders')

        ->onDelete('cascade');
    $table->foreign('product_item_id')

        ->references('id')

        ->on('product_items')

        ->onDelete('cascade');
    $table->foreign('product_id')

        ->references('id')

        ->on('products')

        ->onDelete('cascade');
    $table->timestamps();

这里模型包含关系和急切负载属性

protected $with = ['order', 'item', 'product'];

public function item()
{
    return $this->hasOne(ProductItem::class, 'id');
}

public function product()
{
    return $this->hasOne(Product::class, 'id');
}

public function order()
{
    return $this->hasOne(Order::class, 'id');
}

当我尝试从此模型中获取数据时,得到的响应是“我将忽略对象的不重要属性

 Collection {#1478 ▼
  #items: array:2 [▼
    0 => OrderItem {#1071 ▼
      #guarded: []
      #with: array:3 [▼
        0 => "order"
        1 => "item"
        2 => "product"
      ]
      -amount: null
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:7 [▼
        "id" => 1
        "order_id" => 1
        "product_item_id" => 1
        "product_id" => 1
        "days" => 0
        "created_at" => "2018-07-10 08:15:02"
        "updated_at" => "2018-07-10 08:15:02"
      ]
      #original: array:7 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:3 [▼
        "order" => Order {#1166 ▶}
        "item" => ProductItem {#1265 ▶}
        "product" => Product {#1366 ▶}
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
    }
    1 => OrderItem {#1072 ▼
      #guarded: []
      #with: array:3 [▼
        0 => "order"
        1 => "item"
        2 => "product"
      ]
      #connection: "mysql"
      #attributes: array:7 [▼
        "id" => 21
        "order_id" => 1
        "product_item_id" => 15
        "product_id" => 4
        "days" => 0
        "created_at" => "2018-07-10 12:44:32"
        "updated_at" => "2018-07-10 12:44:32"
      ]
      #original: array:7 [▶]
      #relations: array:3 [▼
        "order" => null
        "item" => null
        "product" => null
      ]
    }
  ]
}

我确定我的外键值正确分配了100%

问题是..作为响应,我正确地渴望加载第一个对象,但是第二个对象返回null!虽然有产品的ID为4,而product_item的ID为15!任何人都可以帮助您了解发生了什么事情?

0 个答案:

没有答案