Answer the question
In order to leave comments, you need to log in
How can the method be improved?
The task is to display on the page all products from the table of products and for each product of its category. Many-to-many relationship.
There is a ProductController controller, it contains the code:
public function getPart()
{
$cat2prod = [];
$idArr = [];
$result= Product::paginate(8)->toArray();
foreach ($result['data'] as $productInfo) {
$idArr[] = $productInfo['id'];
}
$products = Product::find($idArr);
foreach ($products as $product){
$cat2prod[$product['id']] = $product->categories->toArray();
}
foreach ($result['data'] as $ind => $productInfo) {
$result['data'][$ind]['categories'] = $cat2prod[$productInfo['id']];
}
return $result;
class Product extends Model
{
public function categories()
{
return $this->belongsToMany('App\Category','product_categories');
}
}
Answer the question
In order to leave comments, you need to log in
It's better to use with.
$result = Product::paginate(8)->with('categories')->toArray();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question