Home > Software engineering >  Many to many Laravel issue models?
Many to many Laravel issue models?

Time:12-28

There are two models:

class Specialization extends Model
{
    use HasFactory;

    public $timestamps = false;

    protected $fillable = ['name', 'parentid'];

    public function scopeActive($query)
    {
        return $query->where('status', true);
    }

    public function services()
    {
        return $this->hasMany(Service::class);
    }
}

class Service extends Model
{
    use HasFactory;

    public function specializations()
    {
        return $this->belongsToMany(Specialization::class);
    }
}

Each specialization has many services. I try to get them:

 public function services(Specialization $specialization)
    {


        $specializations = $specialization->services()->get();


        return response()->json($specializations);
    }

As result I got this error:

"message": "PDO: SQLSTATE[42703]: Undefined column: 7 ОШИБКА:  столбец services.specialization_id не существует\nLINE 1: select * from \"services\" where \"services\".\"specialization_id...\n                                       ^ (SQL: select * from \"services\" where \"services\".\"specialization_id\" = 1 and \"services\".\"specialization_id\" is not null)"

}

Why is field specialization_id looking in services table instead third table?

CodePudding user response:

You should have belongsToMany on both relationships.

class Specialization extends Model
{
    public function services()
    {
        return $this->belongsToMany(Service::class);
    }
}
class Service extends Model
{
    use HasFactory;

    public function specializations()
    {
        return $this->belongsToMany(Specialization::class);
    }
}

The default pivot table name will be service_specialization I think. If you want to change it, pass it as the 2nd parameter.

  • Related