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 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站