Can anyone help me on how to save many to many relationship? I have tasks, user can have many tasks and task can have many users (many to many), What I want to achieve is that in update form admin can assign multiple users to specific task. This is done through html multiple select input

name="taskParticipants[]"

这里的问题是,通过相同的表单(输入),您可以添加/删除用户,这就是为什么我必须使用sync().

This is my User model:

public function tasks()
{
    return $this->belongsToMany('Task','user_tasks');
}

Task model

public function taskParticipants()
{
    return $this->belongsToMany('User','user_tasks');
}

TaskController

public function update($task_id)
{
    if (Input::has('taskParticipants'))
    {
        foreach(Input::get('taskParticipants') as $worker)
        {
            $task2 = $task->taskParticipants->toArray();
            $task2 = array_add($task2,$task_id,$worker);
            $task->taskParticipants()->sync(array($task2));
        }
    }
}

This is structure of tables tasks id|title|deadline

user_tasks
id|task_id|user_id

推荐答案

tldr; Use 100 with 2nd param 101


Many-to-many relationship is belongsToMany on both models:

// Task model
public function users()
{
  return $this->belongsToMany('User', 'user_tasks'); // assuming user_id and task_id as fk
}

// User model
public function tasks()
{
  return $this->belongsToMany('Task', 'user_tasks');
}

In order to add new relation use attach or sync.

两者的区别在于:

1 attach will add new row on the pivot table without checking if it's already there. It's good when you have additional data linked to that relation, for example:

UserExam与枢轴表attempts: id, user_id, exam_id, score相连

我想这并不是你所需要的:

$user->tasks()->getRelatedIds(); // [1,2,3,4,5,6]

$user->tasks()->attach([5,6,7]);
// then
$user->tasks()->getRelatedIds(); // [1,2,3,4,5,6,5,6,7]

2 sync on the other hand, will either remove all relations and set them up anew:

$user->tasks()->getRelatedIds(); // [1,2,3,4,5,6]

$user->tasks()->sync([1,2,3]);
// then
$user->tasks()->getRelatedIds(); // [1,2,3]

或者,它将在不分离先前关系和不添加重复项的情况下设置新关系:

$user->tasks()->sync([5,6,7,8], false); // 2nd param = detach
// then
$user->tasks()->getRelatedIds(); // [1,2,3,4,5,6,7,8]

Laravel相关问答推荐

Laravel将变量从模板到已发布的供应商模板

Livewire 基于下拉 Select 自动填充输入框

如何通过 Eloquent 获取单个集合中每位教师的学生人数

Laravel:BelongstoMany 关系实现

如何通过单击进入 vs 代码中的类

Laravel/Eloquent:致命错误:在非对象上调用成员函数 connection()

Laravel 5 - 手动分页

Laravel 5 make:控制器在应用程序文件夹而不是控制器文件夹中创建控制器

SQLSTATE [42000]:语法错误或访问冲突:1066 Not unique table/alias on relationship

条带 api 判断现有卡

如何使用中间件将标头添加到响应中?

如何在 Laravel 中使用旧输入重定向?

如何在 Laravel 查询中使用多个 OR、AND 条件

Laravel 迁移命名约定

脚本 php artisan clear-compiled 处理 pre-update-cmd 事件返回错误(Laravel 4.1 升级)

Laravel 验证 pdf mime

如何在 Laravel 或 Redis 中取消排队的作业(job)

如何让 Laravel 将 View 的Content-Type标头返回为application/javascript?

如何在 Laravel 5.3 中获取当前的语言环境

Laravel Mix:更新 Node.js 依赖项