cac
1 month ago

L8 Many to Many returning only 1 record

Posted 1 month ago by cac

I set a a many to many relationship with the belongsToMany method on both models. I am able to attach and detach all right. But when I try to retrieve the entire collection only record is returned.

Returning 1 record

$e->workouts

Returning all records

$e->workouts()->get()

I dont quite understand why the first approach is not returning all records. An enlightenment please?

Models:

class Exercise extends Model
{
    use SoftDeletes, HasFactory;

    protected $guarded = [];

    public function workouts()
    {
        return $this->belongsToMany(Workout::class);
    }
}

class Workout extends Model
{
    use SoftDeletes, HasFactory;

    protected $guarded = [];

    public function exercises()
    {
        return $this->belongsToMany(Exercise::class);
    }
}

Migrations:

 Schema::create('exercises', function (Blueprint $table) {
            $table->id();
            $table->foreignId('exercise_id')->nullable()->comment('replacement exercise');
            $table->string('name')->unique();
            $table->text('description');
            $table->string('video_url')->nullable();
            $table->timestamps();
            $table->softDeletes();
        });

 Schema::create('workouts', function (Blueprint $table) {
            $table->id();
            $table->integer('series');
            $table->string('description')->index()->nullable();
            $table->string('name')->index()->nullable();
            $table->integer('repetitions');
            $table->timestamps();
            $table->softDeletes();
        });

Schema::create('exercise_workout', function (Blueprint $table) {
            $table->id();
            $table->foreignId('workout_id');
            $table->foreignId('exercise_id');
            $table->timestamps();
        });

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