Laravel:将belongsTo逻辑转换为belongsToMany的最佳方法是什么?

My app is about artists painting walls.

At this point an artist has many walls and a wall belongs to an artist.

But now I want to make possible a Wall to belongsToMany Artists. (sometimes a wall is painted by 2 or more artists...)

I can't figure myself the best way to solve that. What about:

1 - a pivot table : artist_wall where Wall belongsToMany Artists and Artist hasMany Walls

• is it possible? or must i have belongsToMany relationship on both side?

• I have already 150+ wall records with artist_id field. Feels like a risky mission to transfer the relationship in the pivot table

2 - an array of artist_ids in my wall table

• then i guess i will loose the benefit of the eloquent relationship

• looks dirty

Any experience to share? is it clear enough? I'm using Laravel 5.

Thanks!

You have a many to many relationship. You should have 3 tables:

  • Artists (ID, Description, ...)
  • Artists_Walls (ArtistID, WallID, ...)
  • Walls (ID , Description, ...)

Then you can use joins to get for example all the walls for an artist like this:

select * from Artists a
inner join Artists_Walls aw on a.ID = aw.ArtistID
where a.ID = '1'

If you want the opposite then you do the contrary by joinning Walls on Artists_Walls