Heimdall
6 months ago
1293
5
General

Only one display on relation with pivot table

Posted 6 months ago by Heimdall

Hello

I have problem and i don't know how resolve it ...

I have 3 table : dish / category and pivot table

Each dish can belong to several categories and each category can have several dishes

My pivot table:

public function up()
{
    Schema::create('category_dishes', function (Blueprint $table) {
        $table->id();
        $table->integer("categories_id");
        $table->integer("dishs_id");
        $table->timestamps();
    });
}

My dish table :

    public function up()
    {
        Schema::create('dishs', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("price");
            $table->string("description");
            $table->string("image");
            $table->timestamps();
        });
    }

My table category:

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->string("icon");
            $table->timestamps();
        });
    }

My model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $table = 'categories';

        public function Dishes()
    {
        return $this->belongsToMany('App\Dishs', 'category_dishes', 'dishs_id', 'categories_id');
    }
}

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Dishs extends Model
{
    protected $table = 'dishs';

    public function Category()
    {
        return $this->belongsToMany('App\Category', 'category_dishes', 'categories_id', 'dishs_id')->withPivot('id', 'categories_id', 'dishs_id');;
    }
}

and my controller :

     $dish_by_category = Category::with('dishes')->get();
      dd($dish_by_category);

and when i display this i have :

Illuminate\Database\Eloquent\Collection {#297 ▼
  #items: array:2 [▼
    0 => App\Category {#314 ▼
      #table: "categories"
      #connection: "mysql"
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:6 [▶]
      #original: array:6 [▶]
      #changes: []
      #casts: []
      #classCastCache: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▼
        "dishes" => Illuminate\Database\Eloquent\Collection {#322 ▼
          #items: array:1 [▼
            0 => App\Dishs {#327 ▶}
          ]
        }
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #fillable: []
      #guarded: array:1 [▶]
    }

But i have 3 dish for category and not one....

Ty

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