Laravel - Save data in the database only if it does not exist and....

Asked

Viewed 1,578 times

1

I have a person registration system and there is an area with several checkbox fields that represent the social group 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

group person

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:

Personal controller

    $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 from the table the groups I uncheck and save the selected ones only if they don’t exist yet.

I tried using "save" because they say it already does this check but it didn’t 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));

        }
  • Do you know Sync or attach e dettach? Here’s what you’ll find... https://laravel.com/docs/5.2/eloquent-relationships#inserting-Many-to-Many-relationships if I can’t make a model later today. Abs

  • Never used and it’s very complex kkkk I’ll see if I understand.

  • It’s quiet, in fact. your link table doesn’t need id, it can only have the two keys of the person and group table both as the primary key and will be even faster the search. Do a simple test first and you will see that it is very simple. I have something ready, but I could not find it here. I will send you a ready example later. Abs

  • That’s what João’s answer is. I couldn’t finish it... but I will do it soon to stay as a reference, it follows: https://github.com/code-sample/laravel-many-to-many I must finish hj the night or tomorrow. I have to do the views... if you want to help. Abs

1 answer

1

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

In his case I noticed that he placed a primary key that identifies each record of his table, and two fields that are the ones that relate the primary keys. Is it accurate (redundant) ???

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

Table Person (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');
    }
}

Table Group (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 case you have to stay with 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 table, in his case the id comes in front, but in the configuration placed it works the same way rewriting the way of Eloquent know the name of the field that relates.

The question now boils down to this simple and easy command Sync, where it checks when sending the information array what information has in the table there it does nothing, which has it inserts as new record and which have been removed it removes. Actually this command on a detach and a attach of Eloquent sequentially.

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

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

Read:

Eloquent Manytomany - Many Relationships for Many

github - code-sample/Laravel-Many-to-Many

  • 1

    Cool John well that. I will make a model for future reference. I see that this is a recurring issue with Laravel. I’m starting here: https://github.com/code-sample/laravel-many-to-many

  • Good @Evert cool ... too ... congratulations, I will put your link in the reply!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.