Do a HasMany by date with Laravel 5.3?

4

Is there any way to do HasMany by bringing records by date?

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

I tried to use the following but did not scroll:

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

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

    
asked by anonymous 22.11.2016 / 11:38

1 answer

3

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.

    
22.11.2016 / 11:40