Definition in the relationship
In Laravel, you can add a where clause in a method that defines the relationship between entities.
See:
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 be consulting by month and year, I suggest using the whereMonth
and whereYear
methods to do this.
See:
public function despesasMes()
{
return $this->despesas()
->whereMonth('data_vencimento', '=', date('m'))
->whereYear('data_vencimento', '=', date('Y'));
}
Definition in query:
Another interesting way to work is to define the condition of which month and year are the desired expenses at the time of the query, not the relationship statement.
See:
$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 despesas
that are within the where
condition set in Closure
will be returned.