staudenmeir / eloquent-has-many-deep

Laravel Eloquent HasManyThrough relationships with unlimited levels
MIT License
2.67k stars 157 forks source link

Category -> hasMany -> Post -> belongsTo -> User #180

Closed jesperbjoernandersen closed 1 year ago

jesperbjoernandersen commented 1 year ago

I'm trying to get all users who has posted in the given category. The relationships are as described in the title. How would I go about accomplishing this? Tried with hasManyDeepFromRelations, but that doesn't seem to work.

staudenmeir commented 1 year ago

Hi @jesperbjoernandersen,

Tried with hasManyDeepFromRelations, but that doesn't seem to work.

What code did you try? What didn't work?

jesperbjoernandersen commented 1 year ago
class Category extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class)
    }

    public function users()
    {
        return $this->hasManyDeepFromRelations($this->posts(), (new Post())->user());
    }
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class)
    }
}

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class)
    }
}
staudenmeir commented 1 year ago

What didn't work? What query did you execute? Is there an error?

jesperbjoernandersen commented 1 year ago

Okay, I deleted everything and rewrote the code. Now it works. Must have had a typo or something somewhere. It just returned nothing. Like an empty collection, but now the collection is filled. My bad, sorry.

decadence commented 1 year ago

In this scenario will be duplicated users or only unique in relationship result? If category has multiple posts from the same user.