dongpo2002 2014-01-26 07:54
浏览 52
已采纳

Laravel 4:数据透视表或ID

users
id
email
password
created_at
updated_at

tasks
id
name
created_at
updated_at

Should I create a pivot table (users_tasks), or just put a user_id field within the tasks table? I'd like to use the Eloquent driver, but I'm not sure which method would be the most appropriate for these kinds of relationships...

Many-to-many relations are a more complicated relationship type. An example of such a relationship is a user with many roles, where the roles are also shared by other users. For example, many users may have the role of "Admin".

From that quote on the Laravel documentation, it stands to reason that in this scenario, there is no need for a pivot table... since each task is only owned by a single user ... is that the right way of thinking?

  • 写回答

1条回答 默认 最新

  • dongshi1869 2014-01-26 08:35
    关注

    Correct, if each task is only ever owned by a single user then adding a user_id column to the tasks table will be the simplest option, and the relationships would be set up in the Models something like:

    class User extends Eloquent {
    
        public function tasks()
        {
            return $this->hasMany('Task');
        }
    
    }
    
    class Task extends Eloquent {
    
        public function user()
        {
            return $this->belongsTo('User');
        }
    
    }
    

    EDIT

    If you are planning at any stage to allow multiple users to have access to tasks, eg. if you want the owner to be able to assign tasks to others then you are probably best to use a pivot table. You could add one in later, but possibly cleaner to do it up front if that is the plan. As well as providing the relationship the pivot table could also include the status/access details of the user. You would then add a task_user table, something like:

    task_user
        -task_id
        -user_id
        -status_id
    

    with the status_id indicating if the user is the owner or the item has been assigned to them. You would then change the User model tasks method to return a $this->hasMany relationship.

    If you are going to add more than just the task and user ids to the pivot you need to include the pivot table field details in your relationship definition, eg.

    return $this->belongsToMany('Task')->withPivot('status_id');
    

    see http://laravel.com/docs/eloquent#working-with-pivot-tables

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!