One To Many (1-N) relation in Laravel backpack

4.5k views Asked by At

I'm using Laravel BackPack CRUD. I have a 1-N (One To Many) relation between two tables :

  • a personne belongs to one structure
  • in a structure there is many personnes

So i have a personnes table :

idPersonnes, name, firstname, idStructures

And a structure table :

idStructures, name, adress

In my personne Model i have :

public function structure()
{
     return $this->belongsTo('App\Models\Structure', 'idStructures', 'idStructures');
}

In my personne controller i have :

$this->crud->addField([
            'label' => 'Structure',
            'type' => 'select2',
            'name' => 'idStructures', // the db column for the foreign key
            'entity' => 'structure', // the method that defines the relationship in your Model
            'attribute' => 'nom', // foreign key attribute that is shown to user
            'model' => 'App\Models\Structure' // foreign key model
        ]);

This is working well. I have select2 dropdown when i edit a personne and i can choose and save a structure.

Now when i edit a structure i want to show all the personnes that belongs to that structure. In my structure model i have :

public function personnes()
{
    return $this->hasMany('App\Models\Personne', 'idStructures', 'idStructures');
}

In my structure controller i have :

$this->crud->addField([
            'label' => 'Personnes',
            'type' => 'select2',
            'name' => 'idStructures', // the db column for the foreign key
            'entity' => 'personnes', // the method that defines the relationship in your Model
            'attribute' => 'nom', // foreign key attribute that is shown to user
            'model' => 'App\Models\Personne' // foreign key model
        ]);

It's not working. Am i doing something wrong ? Thanks for your help.

2

There are 2 answers

0
tabacitu On
0
Jordan On

It seems you should use

select2_multiple

in this case.

$this->crud->addField([
                'label' => 'Personnes',
                'type' => 'select2_multiple',
                'name' => 'idStructures', // the db column for the foreign key
                'entity' => 'personnes',
                'attribute' => 'nom', // foreign key attribute that is shown to user
                'model' => 'App\Models\Personne' // foreign key model
        ]);

Let me know if this helped