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

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!

图片转代码服务由CSDN问答提供 功能建议

我的应用程序是关于艺术家绘画墙。

此时艺术家 有很多墙,墙是属于艺术家的。

但现在我想让Wall成为一名艺术家。 (有时一面墙是由两位或更多艺术家绘制的......)

我无法想象自己解决这个问题的最佳方法。 那么:

1 - 数据透视表:artist_wall 其中Wall属于多个艺术家 和艺术家有多个墙

•是吗? 可能? 或者我必须在两边都有belongsToMany关系?

•我已经有150多个带有artist_id字段的墙记录。 感觉就像在数据透视表中传输关系一样冒险的任务

2 - 我的墙表中的artist_ids数组

•然后我想我将失去雄辩关系的好处

•看起来很脏

有经验可以分享吗? 它是否足够清楚? 我正在使用Laravel 5.

谢谢!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题