Do a Hasmany per date with Laravel 5.3?

Asked

Viewed 122 times

4

Is there any way to make a HasMany bringing records by date?

public function despesas()
{
    return $this->hasMany(Despesa::class); //registros apenas desse mês
}

I tried to use the following, but it didn’t roll:

public function despesaMes()
{
    return DB::table('despesa')->whereDate('data_vencimento' , '=', date('Y-m'))->get();
}

The saved format is Y-m-d H:i:s

1 answer

3


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

  • 1

    It worked buddy, thank you very much

Browser other questions tagged

You are not signed in. Login or sign up in order to post.