7
Good, I have the following problem when using Laravel 5 in the relationship of tables:
I have these 4 tables (hypothetical names to illustrate the problem):
Using the Laravel 5 models I connected them to each other:
Modelo Empresa
public function pessoa(){
return $this->hasMany('App\Pessoas')
}
Model People
public function trabalho(){
return $this->hasMany('App\Trabalho')
}
public function empresa(){
return $this->belongsTo('App\Empresa')
}
Work model
public function custo(){
return $this->hasMany('App\Custo')
}
public function pessoa(){
return $this->belongsTo('App\Pessoa')
}
Modelo Custo
public function trabalho(){
return $this->belongsTo('App\Trabalho')
}
My question is how to make the sum of the cost of all the people in a given company and all the jobs... For example, to know the total cost of a job I do something like:
$trabalho = new Trabalho->find($id)
$custoDoTrabalho = $trabalho->custo->sum('montante')
However, if you do the following:
$pessoas = new Empresa->find($id)->pessoa
$custoDosTrabalhosTodasAsPessoas = $pessoas->trabalho->custo->sum('montante')
Doesn’t work!
To achieve the intended result I have to write many lines (and I am lazy and the project is great and with many cases of these!)
$custo = 0;
$pessoas = new Pessoa->find($id);
$trabalhos = $pessoas->trabalho;
foreach($trabalhos as $trabalho)
$custo+=$trabalho->custo->sum('montante')
Is there any way to use "Eloquent" relationships for this goal, or do I have to write everything down?
(sorry the text so large... thanks in advance!)
I had already asked this question for a long time, however I have already solved the problem (I don’t remember how), but I liked your solution and it seems to me the most correct! Thank you for the reply!
– Ricardo Cruz
I had already asked this question for a long time, however I have already solved the problem (I don’t remember how), but I liked your solution and it seems to me the most correct! Thank you for the reply!
– Ricardo Cruz