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? 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?

Answers


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


Need Your Help

In SQL Server 2005, can I do a cascade delete without setting the property on my tables?

sql-server sql-server-2005 cascade

I have a database full of customer data. It's so big that it's really cumbersome to operate on, and I'd rather just slim it down to 10% of the customers, which is plenty for development. I have an