I have a products table. Would like to attach related product IDs with an extra collection attr related_ids, which will will a custom query (maybe?). So far I have this-
$product = Product::where('id', $id)->first()->toArray();
$related_products = Product::where('id', '!=', $id)->where('category_id', $product['category_id'])->inRandomOrder()->limit(6)->get('id')->map(function($item) {
return $item->id;
});
$product['related_products'] = $related_products;
Any way to do this is one query? I will need this in two place, for single product query, or a list of queried products, like a returned collection but for each product, the related ids will be attached on an extra attribute. Tried this but doesn't work when a new param is added-
$products = Product::where('author', 'randal')
->orderBy('id', 'ASC')
->paginate($per_page);
$products->getCollection()->transform(function ($product) {
$related_products = Product::where('id', '!=', $product->id)->where('category_id', $product->category_id)->inRandomOrder()->limit(6)->get('id')->map(function ($item) {
return $item->id;
});
$product->related_products = $related_products;
return $product;
});
$product->related_products attribute is not appended into the collection at all. Please note that It would be nice if this extra param can be pushed in both for single product query or multiple(for each).
Thanks!