Laravel - Save data in the database only if there is no ...

1

I have a person registration system and there is an area with several checkbox fields that represent the social groups that the current person represents:

TABLES

person

id | nome
1  | João
2  | Maria
3  | Ana

group

id | grupo
1  | Lorem1
2  | Lorem2
3  | Lorem3

personal_group

id | id_grupo | id_pessoa
1  |     1    |      1
2  |     1    |      2
3  |     2    |      1

And I have the following code in my controller to save the changes:

PersonController

    $grupo = $request->grupo; //retornando valores dos campos checkbox

    for($x = 0; $x < count($grupo); $x++){
        array_push($query_grupo, array('id_grupo' => $grupo[$x], 'id_pessoa' => $id));      
    }
    DB::table('grupo_pessoa')->insert($query_grupo);

I need to remove the groups I uncheck from the table and save the selected ones only if they do not already exist.

I tried to use "save" because they say it already does this check but it did not work the way I tried:

$grupo_pessoa = new GrupoPessoa;

        for($x = 0; $x < count($grupo); $x++){
            $grupo_pessoa->id_grupo = $grupo[$x];
            $grupo_pessoa->id_pessoa = $id;
            $grupo_pessoa->save();

            array_push($query_grupo, array('id_grupo' => $grupo[$x], 'id_pessoa' => $id));

        }
    
asked by anonymous 30.05.2016 / 18:27

1 answer

1

In the many to many relationship, it is identified by the primary key of two other tables, forming the set that identifies the primary key of the middle table, that is, the one that receives the two keys.

In your case I noticed that you have placed a primary key that identifies each record in your table, and two fields that are the ones that relate the primary keys. Is it necessary (redundant) ???

In Laravel, the Eloquent ORM does the heavy lifting, so if it is configured as specified below it is a simple command . Exemplifying:

Person table (class pessoa)

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Pessoa extends Model
{
    protected $table      = 'pessoa';
    protected $primaryKey = 'id';
    protected $fillable   = ['nome'];
    public  $timestamps   = false;

    public function grupo()
    {           
        return $this->belongsToMany('App\Grupo','grupo_pessoa','id_pessoa', 'id_grupo');
    }
}

Group Table (class grupo)

    <?php namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Grupo extends Model
    {
        protected $table      = 'grupo';
        protected $primaryKey = 'id';
        protected $fillable   = ['grupo'];
        public  $timestamps   = false;

        public function pessoa()
        {           
            return $this->belongsToMany('App\Pessoa','grupo_pessoa','id_grupo','id_pessoa');
        }
    }

Your table grupo_pessoa in this example case must have two fields only: (Layout)

grupo_pessoa
id_grupo | id_pessoa

The relationship Many To Many is in this format, I had to put the fields in the configuration, because the default would be the name of the tabela , undescore and id of the table , in your case id comes in front, but in the set configuration works the same form rewriting the way Eloquent know the name of the field that relates .

The question now boils down to this simple and easy command sync , where it checks to send the array of information what information it has in the table there it does nothing, which does not have it inserts as new record and the ones that have been removed it removes. In fact this command in a detach is a attach of Eloquent in sequence.

$pessoa = App\Pessoa::findOrFail(1);
$pessoa->grupo()->sync([1,2,3];

This would be the correct and ideal way, following the nomenclature of the persistence Framework itself, the Eloquent in the simple relationship of Many to Many Many to Many

Read

Eloquent ManyToMany - Many Many Relationships

github - code-sample / laravel-many-to-many

    
30.05.2016 / 21:21