Reputation: 167
I have a model called Products, and I need to return the related products to the view. So I created another model called Category, and the relation is many-to-many.
I managed to get the related products but each with a category attached to it which is not quit good, and this my code:
$categories = Product::find($id)->categories;
$products = new Product;
$products = $products->toArray();
foreach ($categories as $cat) {
array_push($products, Category::find($cat->id)->products);
}
return $products;
Is there a better way to do that ?
Upvotes: 0
Views: 1274
Reputation: 167
I did it using regular SQL query and here is the code hoping for helping someone
$catIDs = DB::table('product_category')
->select('category_id')
->where('product_id', $id)
->pluck('category_id');
$productsIDs = DB::table('products')
->select('product_category.product_id')
->distinct()
->rightJoin('product_category', 'products.id', '=', 'product_category.product_id')
->whereIn('category_id', $catIDs)
->pluck('product_id');
$relatedProducts = Product::with('firstImage')
->whereIn('id', $productsIDs)
->where('id', '!=', $id)
->inRandomOrder()
->get();
Upvotes: 1
Reputation: 9045
// Basic usage
$product = Product::findOrFail($id);
$relatedProducts = Product::where('category', $product->category)->get();
// If you want to skip the main product from appearing again in the related products collection do
$relatedProducts = Product::where('category', $product->category)->where('id', '!=', $product->id)->get();
// to simplify this, you can create a method in `Product` model class :
public function getRelatedProducts()
{
return self::where('category', $product->category)->where('id', '!=', $this->id)->get();
}
// and then do :
$product = Product::findOrFail($id);
$relatedProducts = Product::getRelatedProducts();
Upvotes: 0
Reputation: 1
I find many to many relationships troubling in most cases and in such cases it's better to create another table that maps relationships in a one to many fashion. In this case I think it's easier to have a category id column in the products table then when you want to get related products you simply use find products where the category is the same as the one you want eg: $Products::where("product_id",$productId)->get();
Upvotes: 0