akeeba / fof

Rapid Application Development framework for Joomla!™ 3 and 4
0 stars 0 forks source link

Added new saveRelations() method to belongsToMany #600

Closed Skullbock closed 8 years ago

Skullbock commented 8 years ago

Allows to save the relation's "links" without saving the object themselves

Usage

Normal way of saving items + relations

<?php

// The related Ids to attach
$ids = array(1, 2, 3);

$this->find(1);

$roles = $user->getContainer()->factory->model('Roles')->tmpInstance();

$newRoles = $roles->where(
    $roles->getIdFieldName(), 'in', $ids
)->get();

foreach($newRoles as $newRole) {
    $this->roles->add($newRole);
}

$this->getRelations()->save('roles');

This saves the related items themselves before saving the links, which is not always required and kind of heavy in most cases

With this new method you can also do

<?php

// The related Ids to attach
$ids = array(1, 2, 3);

$this->find(1);

$roles = $user->getContainer()->factory->model('Roles')->tmpInstance();

$newRoles = $roles->where(
    $roles->getIdFieldName(), 'in', $ids
)->get();

foreach($newRoles as $newRole) {
    $this->roles->add($newRole);
}

$this->getRelations()->getRelation('roles')->saveRelations();

which will just save the link in the pivot table

nikosdion commented 8 years ago

Thank you! 🙇🏻

Skullbock commented 8 years ago

Should i also update the docs?

nikosdion commented 8 years ago

Yes, please :)

Skullbock commented 8 years ago

Done! https://github.com/akeeba/fof/wiki/Model-relations#saving-just-the-relation-links

nikosdion commented 8 years ago

Thank you!