IT TIP

라 라벨은 다 대다 관계 저장 / 업데이트

itqueen 2020. 10. 30. 21:18
반응형

라 라벨은 다 대다 관계 저장 / 업데이트


누구나 다 대다 관계를 구하는 방법에 대해 나를 도울 수 있습니까? 나는 작업이 있고, 사용자는 많은 작업을 가질 수 있고 작업은 많은 사용자 (다 대다)를 가질 수 있습니다. 내가 달성하고 싶은 것은 업데이트 양식에서 관리자가 특정 작업에 여러 사용자를 할당 할 수 있다는 것입니다. 이것은 html 다중 선택 입력을 통해 수행됩니다.

name="taskParticipants[]"

여기서 문제는 동일한 양식 (입력)을 통해 사용자를 추가 / 제거 할 수 있다는 것입니다. 이것이 제가 sync ()를 사용해야하는 이유입니다. 처음부터 시작해야하지만 어디서부터 시작해야할지 모르겠습니다 ...

이것은 내 사용자 모델입니다.

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

작업 모델

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));
        }
    }
}

이것은 테이블의 구조입니다. 작업 id | title | deadline

user_tasks
id|task_id|user_id

tldr; sync두 번째 매개 변수와 함께 사용false


belongsToMany대다 관계는 두 모델 모두에 있습니다.

// 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');
}

새로운 관계를 추가하려면 attach또는 sync.

둘의 차이점은 다음과 같습니다.

1 attach 은 이미 있는지 확인하지 않고 피벗 테이블에 새 행을 추가합니다. 해당 관계에 추가 데이터가 연결되어 있으면 좋습니다. 예를 들면 다음과 같습니다.

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]

sync반면에 2 는 모든 관계를 제거하고 새로 설정합니다.

$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]

모든 Eloquent 관계를 저장하고 업데이트하는 방법에 대한 제 노트입니다.

에서 일대일 :

당신은 사용할 필요가 hasOne의를 첫 번째 모델과에 에 BelongsTo 두 번째 모델

to add record on the first model (HasOne) use the save function

example:    $post->comments()->save($comment);

to add record on the second model (BelongsTo) use the associate function

example:    $user->account()->associate($account);    $user->save();


in One to Many:

You have to use HasMany on the first model and BelongsTo on the second model

to add record on the first table (HasMany) use the save or saveMany functions

example:    $post->comments()->saveMany($comments);

to add record on the second model (BelongsTo) use the associate function

example:    $user->account()->associate($account);    $user->save();


in Many to Many:

You have to use BelongsToMany on the first model and BelongsToMany on the second model

to add records on the pivot table use attach or sync functions

  • both functions accepts single ID or array of ID’s 

  • the difference is attach checks if the record already exist on the pivot table while sync don’t

example: $user->roles()->attach($roleId);


in Polymorphic One to Many:

You have to use MorphMany on the main model and MorphTo on all the (***able) models

to add records on all the other models use the save

example:    $course->tags()->save($tag);

the pivot table should have the following columns:

. main model ID

. (***able) ID

. (***able) Type


in Polymorphic Many to Many:

You have to use MorphByMany on the main model and MorphToMany on all the (***able) models

to add records on all the other models use the save or saveMany

example:    $course->tags()->save($tag);

example:    $course->tags()->saveMany([$tag_1, $tag_2, $tag_3]);

the pivot table should have the following columns:

. main model ID

. (***able) ID

. (***able) Type


in Has Many Through (shortcut):

You have to use HasManyThrough on the first table and have the normal relations on the other 2 tables

this doesn’t work for ManyToMany relationships (where there’s a pivot table)

however there’s a nice and easy solution just for that.


Here's an article I wrote, inspired by this answer. Important to check it: https://hackernoon.com/eloquent-relationships-cheat-sheet-5155498c209


The sync function obliterates the exiting relationships and makes your array the entire list of relations. You want attach instead to add relations without removing others.

참고URL : https://stackoverflow.com/questions/24702640/laravel-save-update-many-to-many-relationship

반응형