【问题标题】:Laravel 4 belongsToMany with where conditionLaravel 4 belongsToMany with where 条件
【发布时间】:2014-10-30 04:31:01
【问题描述】:

我有以下数据库结构:

卡片表与类型具有多对多关系,类型可以具有以下 3 种元类型之一:

  • 超类型
  • 亚型
  • 类型

在我的卡片模型中,我希望有以下方法:

  • types() -> "... where types.metatype='type'"
  • supertypes() -> "... where types.metatype='supertype'"
  • subtypes() -> “...其中 types.metatype='subtype'”

是否可以在类型表(而不是数据透视表)上添加一个 where 来实现这一点?

在此之前,我有 3 个不同的表:

  • cards_types
  • cards_supertypes
  • cards_subtypes

但这似乎不是一个好主意,因为元类型数据已经存在于类型表中,所以我宁愿不通过复制关系表来“重复”这些信息。

【问题讨论】:

    标签: php laravel-4 many-to-many


    【解决方案1】:

    这可能有效:

    public function supertype() {
        return $this->belongsToMany('Card')->where('metatype','=','supertype');
    }
    
    public function subtype() {
        return $this->belongsToMany('Card')->where('metatype','=','subtype');
    }
    
    public function type() {
        return $this->belongsToMany('Card')->where('metatype','=','type');
    }
    

    【讨论】:

    • 谢谢,我用另一种方式解决了这个问题,但你的答案确实有效:)
    • 你能告诉我们怎么做吗?谢谢:)
    猜你喜欢
    • 2021-07-12
    • 2019-07-08
    • 1970-01-01
    • 2019-05-31
    • 1970-01-01
    • 2019-10-24
    • 1970-01-01
    • 2017-11-05
    • 2017-01-12
    相关资源
    最近更新 更多