3

estoy haciendo un proyecto para la universidad y tengo un problema al trabajar con una tabla pivote, es la relación entre Vacunas (Vaccine) y Mascotas (Pet), es una relación de muchos a mucho, cree las migraciones tanto de Vaccine como de Pet, y de la tabla pivote pets_vaccines. Cree los modelos y sus relaciones pero cuando trato de ocupar la relacion no funciona. Ademas en la tabla pets_vaccines tengo 2 datos (scheduled_date y application_date) que necesito ocupar.

Mi idea es tener una vista donde muestre todos los datos de esa tabla pivote usando Eloquent, pero no puedo ni ingresar a los datos de la tabla pivote ni a los datos de otra tabla de la relación (es decir, si ocupo pets no puedo acceder a los datos de vaccine y viceversa).

Dejare los códigos de todo lo que ocupo para esto:

Modelo Vaccine

public function pets(){
        return $this->belongsToMany('App\Pets');
}

Modelo Pet

public function vaccines(){
        return $this->belongsToMany('App\Vaccine')->withPivot('scheduled_date');
}

VaccineController

public function schedule()
    {
        $pets = Pet::get();

        return view('Vaccines.schedule', compact('pets'));
    }

Migration Pet

Schema::create('pets', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->date('birthdate');
        $table->string('color');
        $table->date('castration_date');
        $table->string('weight');
        $table->string('picture')->nullable();


        //Foreign Keys

        $table->unsignedInteger('breed_id');
        $table->foreign('breed_id')->references('id')->on('breeds');

        $table->unsignedInteger('gender_id');
        $table->foreign('gender_id')->references('id')->on('genders');

        $table->unsignedInteger('type_id');
        $table->foreign('type_id')->references('id')->on('types');

        $table->unsignedInteger('food_id');
        $table->foreign('food_id')->references('id')->on('foods');

        $table->unsignedInteger('client_id');
        $table->foreign('client_id')->references('id')->on('clients');

        $table->softDeletes();


        $table->timestamps();
    });

Migration Vaccine

Schema::create('vaccines', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');

        $table->timestamps();
    });

Migration pets_vaccine

Schema::create('pets_vaccines', function (Blueprint $table) {
        $table->increments('id');
        $table->date('scheduled_date')->nullable();
        $table->date('application_date')->nullable();


        //Foreign Keys

        $table->unsignedInteger('vaccine_id');
        $table->foreign('vaccine_id')->references('id')->on('vaccines');

        $table->unsignedInteger('pet_id');
        $table->foreign('pet_id')->references('id')->on('pets');

        $table->timestamps();
    });

Y en la vista tengo esto:

 @foreach ($pets as $pet)
    Mascota: {{$pet->name}}  Vacuna: {{$pet->pivot->scheduled_date}} <br>
 @endforeach

Aqui, me da error el "scheduled_date", pero si lo quito me deja de dar el error pero no muestra lo que quiero.

1 respuesta 1

2

Según lo que veo en el código, solo estás llamando al modelo pet únicamente, debes llamar la relación y probablemente iterar sobre ella para ver sus datos:

(Teniendo en cuenta que es muchos a muchos, en teoría podría haber más de un registro).

@foreach ($pets as $pet)
  Mascota: {{$pet->name}}

  Vacunas: 
  @foreach ($pets->vaccines as $vaccine)
    {{ $vaccines->pivot->scheduled_at }}
  @endforeach

@endforeach

Lo más probable es que necesites hacer Eager Loading, aunque depende de cómo esté diseñado o de la cantidad de información:

Pet::with('vaccines')->get();

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.