Definition in the relationship
In Laravel, you can add a Where clause to a method that defines the relationship between entities.
Behold:
public function despesas()
{
return $this->hasMany(Despesa::class); //registros apenas desse mês
}
public function despesasMes()
{
return $this->despesas()->where('data_vencimento' , '=', date('Y-m'));
}
Another detail: Since you will consult by month and year, I suggest using the methods whereMonth
and whereYear
to do this.
Behold:
public function despesasMes()
{
return $this->despesas()
->whereMonth('data_vencimento', '=', date('m'))
->whereYear('data_vencimento', '=', date('Y'));
}
Definition in consultation:
Another interesting way to work is to define the condition of which month and year are the expenses desired at the time of consultation, and not in the relationship statement.
Behold:
$relacionamento['despesas'] = function ($query) {
$query->whereYear('data_vencimento' , '=', date('Y'))
->whereMonth('data_vencimento', '=', date('m'));
};
$model = Model::with($relacionamento)->find(1);
So when you access the values of $model->despesas
, only the despesas
who are in condition where
defined in Closure
will be returned.
Well observed, I put the format in the question
– Felipe Paetzold
It worked buddy, thank you very much
– Felipe Paetzold