Kasio, it’s actually quite simple to do the relationships in the Aravel, so let’s go.
The relationship that you want and that makes all logical sense to your problem is Many to Many
N:M -> Many To Many (Muitos para Muitos)
It would look like :D
Model - Institution
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Instituicao extends Model
{
/**
* Definindo que instituição possui várias doações.
*/
public function doacoes()
{
return $this->belongsToMany('App\Doacoes', 'doacao_instituicao', 'instituicao_id', 'doacao_id');
}
}
Model - Donations
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Doacao extends Model
{
/**
* Definindo que doação possui várias instituições.
*/
public function instituicoes()
{
return $this->belongsToMany('App\instituicoes', 'doacao_instituicao', 'doacao_id', 'instituicao_id');
}
}
Ready now you have finished the relationship Many to Many :D
In his Controller
you can use the following way to access the relationship
$instituicao = App\Instituicao::find(1);
foreach ($instituicao->doacoes as $doacao) {
//
}
Or
$doacoes = App\Instituicao::find(1)->doacoes()->orderBy('nome')->get();
//Lembrando que você pode fazer o inverso também :D
Remarks
The Laravel followed a standard of naming tables and foreign key
for your relationships.
To define this relationship, three database tables are required: instituicoes, doacoes, e doacao_instituicao
. To doacao_instituicao
table is derived from the alphabetical order of the related template names and contains the columns doacao_id
and instituicao_id
.
Did using the L5-Repository it wouldn’t be easier for him?
– Tiago Ferezin
Just to make an observation
l5-repositorio
is a layer above, it needs the relationships to be correct and this is done in the model. @Tiagoferezin and the answer is this same.– novic
Thanks for the answer! I resolved so I had to do another gambit to not insert repeated lines example.. same donation id with same institution id... As to recover the relationship I have not yet made but will be displayed was relationship only to the "owner" of the donation............ I’m using the i5 Repository package
– Kasio Eduardo
@Virgilionovicisto da para ser feito no I5 Repository tb
– Tiago Ferezin
@Kasioeduardo avoid sniffing around the codes, otherwise maintenance becomes complicated later.
– Tiago Ferezin