Many to many relationship with the same table

39 Views Asked by At

I have table "projects" with field BasedOnId And I want to create morphToMany relationsship in current table

In resource Projects I create field

BelongsToMany::make(\App\Nova\Projects::label(), 'based', '\App\Nova\Projects')
                    ->searchable()
                    ->singularLabel(\App\Nova\Projects::singularLabel())

And in model Projects I want to create "based" funtion, but how I can do it with same table?

Code

    public function based()
    {
       return $this->belongsToMany('App\Models\Projects', 'projects', 'basedOnId', 'id');
    }

not work

How I can do it?

1

There are 1 best solutions below

1
Johan On

If I understand correctly, it sounds like you have a many-to-many relationship situation. These can be difficult to manage.

Consider using a 'joining table'. This breaks a 'many-to-many' relationship into two 'one-to-many' relationships.

For example: You may have a table with 'student_id' and 'subject_id' fields. But then you realize: One student can have many subjects. One subject can have many students. So we have a many-to-many relationship.

Resolve this by creating a join table with two fields:

  • 'student_id' with Foreign Key constraint to students table
  • 'subject_id' with Foreign Key constraint to subjects table The join table itself has no Primary Key. We now have two 'one-to-many' relationships via the joining table, making life much easier.

Consider reading up on join tables. I hope this helps...