简体   繁体   English

Laravel 4:数据透视表或ID

[英]Laravel 4: Pivot Table, or 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? 我应该创建一个数据透视表( users_tasks ),或只放了user_id的内场tasks表? 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... 我想使用Eloquent驱动程序,但我不确定哪种方法最适合这些关系......

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? 根据Laravel文档中的引用,可以理解在这种情况下,不需要数据透视表......因为每个task只由一个user拥有......这是正确的思维方式吗?

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: 正确,如果每个任务只由一个用户拥有,那么将一个user_id列添加到tasks表将是最简单的选项,并且将在模型中设置关系,如:

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_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. status_id指示用户是否为所有者或者是否已为其分配了项目。 You would then change the User model tasks method to return a $this->hasMany relationship. 然后,您将更改用户模型任务方法以返回$ this-> hasMany关系。

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. 如果要向枢轴添加多个任务和用户ID,则需要在关系定义中包含数据透视表字段详细信息,例如。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM