Laravel - Eloquent Many to Many

Asked

Viewed 402 times

1

I have this structure

Migration from the Exercise table

public function up()
{
    Schema::create('exercicio', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('nome')->unique();
        $table->timestamps();
        $table->time('deleted_at')->nullable();
    });
}

Table Migration Musculature

public function up()
{
    Schema::create('musculatura', function(Blueprint $table)
    {
        $table->increments('id');
        $table->string('nome')->unique();
        $table->timestamps();
        $table->time('deleted_at')->nullable();
    });
}

Migration of the associative table between Exercicio_musculatura

public function up()
{
    Schema::create('exercicio_musculatura', function (Blueprint $table) {
        $table->integer('exercicio_id')->unsigned();
        $table->foreign('exercicio_id')->references('id')->on('exercicio')->onUpdate('cascade')->onDelete('cascade');
        $table->integer('musculatura_id')->unsigned();
        $table->foreign('musculatura_id')->references('id')->on('musculatura')->onUpdate('cascade')->onDelete('cascade');
    });
}

Model of the Table Exercise

use SoftDeletes;
public $timestamps  = true;
protected $table    = 'exercicio';
protected $fillable = ['nome'];
protected $dates    = ['deleted_at'];
//Aqui é o método que retorna todos os exercicios com suas respectivas musculaturas pré cadastradas no banco
//o método vai buscar no segundo parametro deste return "na tabela associativa exercicio_musculatura"
public function musculaturas(){
    return $this->belongsToMany("App\Http\Models\Musculatura", "Exercicio_Musculatura");
}
public function aparelhos(){
    return $this->belongsToMany("App\Http\Models\Aparelho", "Exercicio_Aparelho");
}

Model of the Musculature Table

use SoftDeletes;
public $timestamps  = true;
protected $table    = 'exercicio';
protected $fillable = ['nome'];
protected $dates    = ['deleted_at'];
//Aqui é o método que retorna todos os exercicios com suas respectivas musculaturas pré cadastradas no banco
//o método vai buscar no segundo parametro deste return "na tabela associativa exercicio_musculatura"
public function musculaturas(){
    return $this->belongsToMany("App\Http\Models\Musculatura", "Exercicio_Musculatura");
}
public function aparelhos(){
    return $this->belongsToMany("App\Http\Models\Aparelho", "Exercicio_Aparelho");
}

Model of the Associative Table of Exercicio_musculatura

class Exercicio_Musculatura extends Model
{

}

My question is the following: I am in the controller, and receiving from an AJAX the ID of the musculature from another place, and I want to consult all the exercises related to that musculature, my bank already has in the associative table the id’s very straight. I’m unable to return anything in my query, how can I do this?

  • How is the consultation that is not working? please post

  • DB::('exercise')->Where('id', "=", $musculatura_id)->with('musculaturas')->get();

  • I’m trying to do this query in a controller

  • It is more interesting to use the models class instead of the 'DB' class. But there are some mistakes, I will try to formulate an answer here and you test if it worked.

1 answer

1


In the exercise model:

public function musculaturas()
{
   return $this->belongsToMany("App\Http\Models\Musculatura", "exercicio_musculatura", "exercicio_id", "musculatura_id");
}

In the Model of Musculature:

public function exercicios()
{
   return $this->belongsToMany("App\Http\Models\Exercicio", "exercicio_musculatura", "musculatura_id", "exercicio_id");
}

In the controller you can search:

//busca a musculatura pelo id
$musculatura = Musculatura::find($musculatura_id);
//carrega os relacionamentos
$musculatura->load('exercicios');

Remember that to use the model class Musculatura you have to give a use right below the namespace of the class of your controller:

<?php

namespace App\Http\Controllers;

use App\Http\Models\Musculatura;

First mistake made: in the model the table name is different, in the Migration it is exercicio_musculatura and in the model is Exercicio_musculatura. The belongsToMany function takes as parameters the relationship model, the name of the pivot table, the foreign key belonging to the model, and the key of the other relationship model.

Second, the relationships are eloquent (i.e., between Models), it is interesting to use the class of models. In addition you were searching through her on the exercise table by the muscle id.

Another thing I noticed that the Muscle Model has as a table name 'exercise':

protected $table = 'exercicio';

Table name must be as in the database: protected $table = 'musculatura';

Test there, and anything consult the documentation: https://laravel.com/docs/6.x/eloquent-relationships#Many-to-Many

  • Guy worked out, thank you very much saw! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.