Home > Back-end >  get relations table data is empty
get relations table data is empty

Time:01-28

i am using laravel 8. i am try to get data with many to many relationship but give me empty data for related table

it's database

enter image description here

Order Model

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

Product Model

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

and fetch Query is

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

Result

enter image description here

i am also check

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

give me same result

CodePudding user response:

First, if you are editing your query like this it will work

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

Why? becuse the pivot table.

what is the pivot table? Let me explain.

when you are working with many-to-many relations you must define an intermediate table like your table:order_prodcts. so Laravel here provides some very helpful ways of interacting with this table.

So here’s a database structure:

orders:
   - id
   - title

products:
   - id
   - title

order_product:
   - id
   - title

The final table in the list: order_product is called a pivot table

let's take your example

let's assume our Order model has many Product models that it is related to. After accessing this relationship, we may access the intermediate table using the relation method you are defining on the models like:

1-Your Product Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    //some code

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

2-Your Order Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    //some code

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

Here each Product model we retrieve is automatically assigned a relation method. This relation method contains a model representing the intermediate order_product table.

SO here try to get you orders with your products

public function index()
{

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

Now, there are several things to mention when using pivot.

  • Pivot table fields by default should be only two fields: foreign key to each of the tables order_id product_id

  • Name of the pivot table should consist of singular names

  • Names should be arranged in alphabetical order in your case o is first of p so your table will be called order_product

Finally Thank you for finishing the read I hope you gained any information from this answer

  •  Tags:  
  • Related