【问题标题】:naming convention with Laravel with double morph relations具有双变形关系的 Laravel 命名约定
【发布时间】:2020-05-04 13:29:23
【问题描述】:

当您在 1 个表(模型)上有 2 个变形关系时,Laravel 中正确的命名约定是什么?

例子:

posts
    id - integer
    title - string
    body - text

videos
    id - integer
    title - string
    url - string

buyers
    id - integer
    name - string

sellers
    id - integer
    name - string

comments
    id - integer
    body - text
    commentable1_id - integer // link to video/posts
    commentable1_type - string // type link to video/posts
    commentable2_id - integer // link to buyers/sellers
    commentable2_type - string // type link to buyers/sellers

现在我使用名称 commentable1commentable2 ,但这不是一个很好的 Laravel 方式。我怎样才能以正确的 Laravel 方式做到这一点?

【问题讨论】:

  • 恕我直言,最好的约定是有意义的,您(尤其是其他人)可以轻松理解,尤其是在远离代码几个月后。有什么问题(假设在您的上下文中有意义)content_comment 用于视频/帖子,trader_comment 用于买家/卖家
  • 你有没有得到你要找的答案,如果有,如果你能把它作为答案发布就好了。

标签: laravel polymorphic-associations


【解决方案1】:

我想这将更多地取决于个人喜好,如果我会这样做,我会这样做

commentable1_id would be video_post_id
commentable1_type would be video_post_type
commentable2_id would be buyer_seller_id
commentable2_type would be buyer_seller_type

这对另一个人来说可能会有所不同,但对我来说,这是可以自我解释的,所以我会使用它。考虑到您将保持主要模型名称不变,如果您要更改它,它将相应地更改。

如果你想匹配 laravel 标准。

例如,您的视频属于帖子,列名称将简单地为videoable_type,其他两列分别为videoable_idsellerable_idsellerable_type

Reference

【讨论】:

  • 是的,我知道这是个人偏好,现在我使用 commentable1 和 commentable2 作为名称,但这不是一个非常漂亮的解决方案...
  • @angelique000 用 Laravel 标准更新了我的答案。
  • 恐怕可销售和可视频的名称不是 Laravel 的方式。 Laravel 总是在模型名称后面使用带有“-able”的模型名称。但我的问题是:我在 1 个模型上有 2 个变形关系。
  • @angelique000 两个变形关系有什么问题,您都应该使用 {ModelName} 简单,如果您有多个变形关系,则没有提及,您将使用不同的命名标准,您将照着做,简单。
猜你喜欢
  • 2014-03-12
  • 1970-01-01
  • 1970-01-01
  • 2016-09-21
  • 1970-01-01
  • 1970-01-01
  • 2017-02-01
  • 2018-10-16
  • 2021-08-07
相关资源
最近更新 更多