Search code examples
laravel-livewire

how to group this relationship in the laravel?


I am trying to group users by date that is in the relationship accesses and page this result.

Model User

public function acessos()
{
    return $this->hasMany(Acessos::class,'id_usuario');
}

Model Acessos

public function user()
{
    return $this->belongsToMany(User::class,'id_usuario');
}

Livewire component

$data = User::query()
            ->search($this->search)
            ->with('acessos')
            ->has('acessos')
            ->paginate($this->perPage);

return view('livewire.relatorios.acessos.acessos-component',[
             'data' => $data
         ]);

Solution

  • Remove the user() method from Acessos Model and change the hasMany() method to belongsToMany in User model's acessos method. This Will solve your problem.

    Remove this:

    public function user()
    {
        return $this->belongsToMany(User::class,'id_usuario');
    }
    

    And change this:

    public function acessos()
    {
        return $this->belongsToMany(Acessos::class,'id_usuario');
    }