afghany
1 year ago

i have problem with Eager Load Laravel

Posted 1 year ago by afghany

hey guys .. i got a problem with eager load while fetching data from my model i eager load 3 relations , to understand the problem here is the migration from my model i fetch from it

$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();

and here the model contains the relation and eager load attribute

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

when i am try to fetch my data from this model here the response i got "i will ignore un-important attributes from object"

Collection {#1478 ▼ #items: array:2 [▼ 0 => OrderItem {#1071 ▼ #guarded: [] #with: array:3 [▼ 0 => "order" 1 => "item" 2 => "product" ] #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 [▶] #relations: array:3 [▼ "order" => Order {#1166 ▶} "item" => ProductItem {#1265 ▶} "product" => Product {#1366 ▶} ] }

1 => OrderItem {#1072 ▼
  #guarded: []
  #with: array:3 [▶]
  #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
  ]

}

] }

i am sure my foreign keys values are assigned correctly 100%

the problem is .. in first object in response i got my eager load correctly but second object it's return null !! while there is product have id 4 and product_item have id 15 !! anyone can help to know what's going on ?

Please sign in or create an account to participate in this conversation.