Проект состоит из четырех связанных таблиц:
1. orders (id, status, client_email, partner_id)
2. order_products (id, order_id, product_id, quantity, price)
3. partners (id, email, name)
4. prods* (id, name, price, vendor_id)
*таблица products есть и используется под другие функции, поэтому использую здесь "prods"
создаю 4 модели:
<?php
//App\Order.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $fillable = [
'id', 'status', 'client_email', 'partner_id',
];
public function partner()
{
return $this->belongsTo('App\Partner');
}
public function order_product()
{
//belongsToMany - возвращает server error
return $this->belongsTo('App\Prod', 'order_products');
}
public function prod()
{
return $this->belongsTo('App\Prod');
}
}
<?php
//App\Partner.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Partner extends Model
{
protected $fillable = ['id', 'email', 'name'];
public function order()
{
return $this->hasOne('App\Order');
}
}
<?php
//App\Order_product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order_product extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
public function order()
{
return $this->hasOne('App\Order');
}
}
<?php
//App\Prod.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Prod extends Model
{
protected $fillable = ['order_id', 'product_id', 'name', 'quantity', 'price'];
public function order()
{
//получить все имена продуктов в заказе
//
return $this->hasManyThrough('App\Order', 'App\Order_product');
}
}
Далее создаю Order Resource:
<?php
//App\Http\Resources\Order.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Order extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'status' => $this->status,
'client_email' => $this->client_email,
'partner_id' => $this->partner_id,
'partner_name' => $this->partner->name,
//возвращает server error
'product_id' => Prod::collection($this->order_product),
'name' => $this->prod->name,
];
}
}
создаю Prod Resource:
<?php
//App/Http/Resources\Prode.php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Prod extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'price' => $this->price,
];
}
}
И возвращаю в Order Controller:
<?php
//App\Http\Controllers\Api\OrderController.php
namespace App\Http\Controllers\Api;
use App\Order;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Http\Resources\Order as OrderResource;
class OrderController extends Controller
{
public function index()
{
$orders = Order::with(['partner', 'order_product', 'prod'])->get();
return OrderResource::collection($orders);
}
}
Как я могу получить название продукта в заказе?