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

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

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog