Laravel多对多关系查询

编程入门 行业动态 更新时间:2024-10-23 13:22:49
本文介绍了Laravel多对多关系查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在构建一个带有用户表和活动表的Laravel应用程序,并通过称为分配的数据透视表实现活动和用户之间的多对多关系:

I am building a Laravel application with a users table and an activities table, and a many-to-many relationship between activities and users implemented with a pivot table called assignments:

  • 用户:id,...
  • 活动:id,...
  • 分配:id,activity_id,user_id,...

我需要记录用户每次完成活动的时间.用户可以多次完成相同的活动.我正在尝试确定在数据库中建模的最佳方法.据我所知,这些选项是:

I need to keep a record of each time a user completes an activity. A user can complete the same activity many times. I am trying to decide on the best way to model this in the database. The options as far as I can see are:

  • 表补全:id,assignment_id,...
  • 第二个数据透视表补全:id,activity_id,user_id,...
  • 我可以创建迁移等.但是,我在Model类及其关系方法方面苦苦挣扎.特别是对于上面的第一个选项,我将如何定义所需的Model类和关系方法?

    I can create the migrations etc. However I am struggling with the Model classes and their relationship methods. In particular, for the first option above, how would I define the required Model classes and relationship methods?

    推荐答案

    好吧,除了活动跟踪之外,您几乎可以对所有内容进行排序.所以,这是我的建议:

    Well, you have pretty much everything sorted except the activity tracking. So, here's what I propose:

    用户表

    带有列ID,名称,电子邮件等

    with columns id, name, email, etc

    活动表

    带有列ID,名称等

    用户活动表(枢轴)

    user_activity table (pivot)

    具有列ID,用户ID,活动ID等 该表将包含用户和活动之间的多对多映射.

    with columns id, user_id, activity_id, etc This table will contain the many to many mapping between users and activities.

    activity_tracking

    activity_tracking

    具有列ID,user_activity_id,状态,updated_at等 在这里,您可以使用整数值表示状态,比如说1.然后,使用updated_at和created_at可以跟踪活动的开始和完成时间.

    with columns id, user_activity_id, status, updated_at etc Here you could use an integer value for status to signify completion lets say 1. And using updated_at and created_at you could track activity start and completion timing.

    更多推荐

    Laravel多对多关系查询

    本文发布于:2023-10-25 08:53:03,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1526490.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:关系   Laravel

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!