dthswrp84966 2016-02-01 13:59
浏览 307
已采纳

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!

  • 写回答

1条回答 默认 最新

  • dstk51319 2016-02-01 15:05
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 正弦信号发生器串并联电路电阻无法保持同步怎么办
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)