Dynamic relationship property returning empty collection
mokhosh opened this issue · comments
I have User
s who have many Purchase
s which belong to many Product
s, 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']
);
}
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?
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.
Please share the whole User
model.
🤦♂️
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!