staudenmeir / eloquent-has-many-deep

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

Dynamic relationship property returning empty collection #212

Closed mokhosh closed 1 year ago

mokhosh commented 1 year ago

I have Users who have many Purchases which belong to many Products, and I want to have a products relationship on the User model. The issue is I can access products just fine by saying $user->products()->get() but $user->products returns an empty collection. I've tried both manual and "using current relationships" methods, and both have this issue.

// User class
public function products()
{
    return $this->hasManyDeepFromRelations(
        $this->purchases(),
        (new Purchase)->products(),
    );
}

// second attempt
public function products()
{
    return $this->hasManyDeep(
        Product::class,
        [Purchase::class, 'product_purchase']
    );
}
staudenmeir commented 1 year ago

Hi @mokhosh, Have you compared the executed queries of $user->products()->get() vs. $user->products?

Does the users table have a column named products by any chance?

mokhosh commented 1 year ago

This is the query for products()->get():

select `products`.*, `purchases`.`user_id` as `laravel_through_key` from `products` inner join `product_purchase` on `product_purchase`.`product_id` = `products`.`id` inner join `purchases` on `purchases`.`id` = `product_purchase`.`purchase_id` where `purchases`.`user_id` = 1;

and this is the one for products property:

select `products`.*, `cart_product`.`cart_id` as `pivot_cart_id`, `cart_product`.`product_id` as `pivot_product_id`, `cart_product`.`quantity` as `pivot_quantity` from `products` inner join `cart_product` on `products`.`id` = `cart_product`.`product_id` where `cart_product`.`cart_id` = 1

I don't have products field on users table.

staudenmeir commented 1 year ago

Please share the whole User model.

mokhosh commented 1 year ago

🤦‍♂️

I started removing irrelevant code from the model to share it here and I found this:

public function getProductsAttribute()
{
    return $this->cart->products;
}

Sorry for taking your time. Thanks!