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

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

报告相同问题?

悬赏问题

  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?