Answer the question
In order to leave comments, you need to log in
Query with relationships in Eloquent: Relationships how to compose?
There are 3 models Category, Product, Product Attributes
class Category extends Model
{
/**
* Category has many Products.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function products()
{
return $this->belongsToMany(Product::class)->withTimestamps();
}
}
class Product extends Model
{ /**
* Product has many Categories.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function categories()
{
return $this->belongsToMany(Category::class)->withTimestamps();
}
}
class Attribute extends Model
{
/**
* Attribute has many Products.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function products()
{
return $this->belongsToMany(Product::class)->withTimestamps();
}
}
class CatalogController extends Controller
{
/**
* Display the specified resource.
*
* @param $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$products=Category::with('products', 'attributes')->where('id', $id)->orWhere('slug', $id)->first();
//dd($products);
return view('catalog.index')->with('products', $products);
}
}
Answer the question
In order to leave comments, you need to log in
Alexey pointed to the documentation but did not take into account that I have connections through a pivot table and the solution is not suitable for this case
. There is a package that basically solves this problem, but I did it in a simple way:
/**
* Display the specified resource.
*
* @param $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$data=Category::with('products')->where('id', $id)->orWhere('slug', $id)->first();
$data->products->map(function ($product) {
$p = Product::find($product->id);
$sizes=[];
foreach ($p->attributes as $a) {
$sizes[]=$a;
}
$product->sizes = $sizes;
return $product;
});
return view('catalog.index')->with('products', $data);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question