Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updating Many to Many? #107

Closed
jakejohns opened this issue Jun 13, 2019 · 0 comments · Fixed by atlasphp/Atlas.Mapper#16
Closed

Updating Many to Many? #107

jakejohns opened this issue Jun 13, 2019 · 0 comments · Fixed by atlasphp/Atlas.Mapper#16

Comments

@jakejohns
Copy link
Contributor

I'm very confused about updating many to many relationships. This is possibly related to #105.

I would think I could just do something like the following:

$instructor_ids = $input['instructor_ids'] ?? [];
unset($input['instructor_ids']);

$session = $atlas->fetchRecord(
    Session::class,
    $session_id,
    ['instructors']
);

$session->instructors = $atlas->fetchRecordset(
    Instructors::class,
    $instructor_ids
);

$session->set($input);
$atlas->persis($session);

But I was unable to make anything even remotely like that work. I ended up having to do this?

$instructor_ids = $input['instructor_ids'] ?? [];
unset($input['instructor_ids']);


$session = $atlas->fetchRecord(
    Session::class,
    $session_id,
    ['instructors']
);

$current = array_map(
    function ($inst) {
        return $inst['instructor_id'];
    },
    $session->instructors->getArrayCopy()
);

// Delete some
foreach ($current as $cur) {
    if (! in_array($cur, $instructor_ids)) {
        $session->instructs->getOneBy(['instructor_id' => $cur])
            ->setDelete();

        $session->instructors->detachOneBy(['instructor_id' => $cur]);
    }
}

// Add some
foreach ($instructor_ids as $instructor_id) {
    if (! in_array($instructor_id, $current)) {
        $session->instructs[] = $this->atlas->newRecord(
            Instruct::class,
            [
                'session_id' => $session->session_id,
                'instructor_id' => $instructor_id
            ]
        );
    }
}

$session->set($input);

$atlas->persist($session);

I feel like I must be missing something, but pouring over the documentation and many attempts only resulted in various exceptions and errors.

Any insight?

jakejohns added a commit to jakejohns/Atlas.Mapper that referenced this issue Feb 20, 2021
Close atlasphp/Atlas.Orm#105
Close atlasphp/Atlas.Orm#107

`setDelete` all through relationships unless they match.
Fixes issue with detaching all related etc.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant