methos's avatar

ManytoMany relationship with equipment table

Hello all! I'm facing something weird. I try to create a relationship between my model car and equipment. I create my cars and equipments table, my car_equipment pivot table :

        Schema::create('equipments', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
       Schema::create('car_equipment', function (Blueprint $table) {
            $table->foreignId('car_id')->constrained();
            $table->foreignId('equipment_id')->constrained();
        });

But when I migrate, I have this error:

"Failed to open the referenced table 'equipment' (Connection: mysql, SQL: alter table `car_equipment` add constraint `car_equipment_equipment_id_foreign` foreig
n key (`equipment_id`) references `equipment` (`id`))"

II should name my table equipment and every things work except that when I dump $car->equipments it's return null. I have to make $car->equipments()->get() to acces to my equipments.

class Car extends Model {
...
public function equipments():BelongsToMany { return $this->belongsToMany(Equipment::class); }
...
}

Someone have an idea ?

Thx in advance

Methos

0 likes
4 replies
tykus's avatar

There is no plural form for equipment. However, you can reference the non-standard name in the FK constraint

$table->foreignId('equipment_id')->constrained('equipments');

Also, set the $table variable on the Equipment model.

$car->equipments it's return null

What queries are being executed?

methos's avatar
methos
OP
Best Answer
Level 1

Hello, thx for the answer. I read that both are correct equipment and equipments but anyway ^^ I prefere use the standart naming ^^

I found the solution ... it's not

$car->equipments

but

$car->equipment

So stupid mistake ^^' Thx again

tykus's avatar

@methos

I read that both are correct equipment and equipments

They are not.

Please or to participate in this conversation.