【问题标题】:define realtion in eloquent orm based on third table基于第三张表以雄辩的形式定义关系
【发布时间】:2014-03-16 16:07:06
【问题描述】:

我有 3 个表,我如何根据绑定它们的合同来定义分类和用户之间的关系?

Taxonomy  : tax_id,name
Users     : user_id,name
contracts : tax_id,user_id,start_time,end_time

SQL: SELECT * FROM taxonomy t where t.tax_id in(select tax_id from contracts where user_id = 3 and DATE() between Start_time and end_time)

但是如何在 eloquent orm 中定义这种关系呢?

【问题讨论】:

    标签: orm laravel relational-database eloquent


    【解决方案1】:

    使用合同作为数据透视表定义分类和用户之间的多对多关系,更多信息请参见docs

    要访问 start_time 和 end_time,您必须在定义 relationship 时指定它们,例如在分类模型中:

    class Taxonomy extends Eloquent {
    
      public function users()
      {
          return $this->belongsToMany('User')->withPivot('start_time', 'end_time');
      }
    
    }
    

    【讨论】:

    • start_time 和 end_time 的条件呢?请问可以提供代码示例来完成答案吗?
    • 我已经更新了答案,包括分类模型中的额外字段,您在指定用户关系时也应该声明它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-10
    • 2020-09-29
    • 2020-06-23
    • 2015-12-05
    • 1970-01-01
    相关资源
    最近更新 更多