Ad
How To Get Rows Related To Same Table Through Many To Many Relationship - Laravel
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 ?
Ad
Answer
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();
Ad
source: stackoverflow.com
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS - Conditionally Load a Different Page
- → Make a Laravel collection into angular array (octobercms)
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?
- → Validating fileupload(image Dimensions) in Backend Octobercms
- → OctoberCMS Fileupload completely destroys my backend
- → How do I call the value from another backed page form and use it on a component in OctoberCms
Ad