There is a Product model and the Category and ProductVariation models associated with it in different ways, which in turn is related to the Image and Property models.
DB structure http://freakytools.ru/storage/images/dbdes.png
class Product extends Model { public function variations() { return $this->hasMany('App\Models\ProductVariation'); } public function categories() { return $this->belongsToMany('App\Models\Category'); } } class ProductVariation extends Model { public function images() { return $this->hasMany('App\Models\Image'); } public function properties() { return $this->hasMany('App\Models\Property'); } } In Category and Image, all fields except name and image_link are hidden, respectively. In the controller, I display all Product with dependencies:
class ProductsController extends Controller { public function index() { return Product::with(['categories', 'variations', 'variations.images', 'variations.properties'])->get(); } } As a result, I get an array of JSON:
[ { "title": "Название продукта", "description": "Описание продукта", "priority": 0, "categories": [ { "title": "category1" }, { "title": "category2" } ], "variations": [ { "slug": "product1_slug", "price": 999, "count": 99, "images": [ { "image_link": "img/products/product1_1.png" }, { "image_link": "img/products/product1_2.png" }, { "image_link": "img/products/product1_3.png" } ], "properties": [ { "title": "Свойство 1", "value": "Значение свойства 1" }, { "title": "Свойство 2", "value": "Значение свойства 2" } ] } ] } ] It would be desirable in the fields 'categories' and 'images' to get an array of values, and not objects with a single field. I understand that you can live with it. But no: D The second day I dance with a tambourine. Thanks for participating!
UPD: While the implementation of this, but I do not want to believe that there is no more elegant way to solve the problem
public function index() { $products = Product::with(['categories', 'variations', 'variations.images', 'variations.properties'])->get(); foreach ($products as $product) { $newCategories = []; $newImages = []; foreach ($product->categories as $category) array_push($newCategories, $category->title); foreach ($product->variations as $variation) { foreach ($variation->images as $image) array_push($newImages, $image->image_link); unset($variation->images); $variation->images = $newImages; } unset($product->categories); $product->categories = $newCategories; } return $products; }