在这个例子中,我得到了一个有效的数组,但是嵌套的数组有不一致的地方
{ "order_id": 1, "status": 20,
"product_id": [
{ "id": 1, "order_id": 1, "product_id": 8, "quantity": 1, "price": 141 },
{ "id": 2, "order_id": 1, "product_id": 30, "quantity": 2, "price": 509 },
{ "id": 3, "order_id": 1, "product_id": 21, "quantity": 1, "price": 399 } ],
"name": { "id": 1, "name": "Product_1", ... "laravel_through_key": 1 }
由于第一个订单中有三个产品,在第二个订单中我已经得到“name”:“Product_4”,即间隔是正确的,并且订单是 prods 表的顺序,而不是 order_products 表的顺序:
{ "order_id": 2, "status": 10,
"product_id": [
{ "id": 4, "order_id": 2, "product_id": 1, "quantity": 3, "price": 320 },
{ "id": 5, "order_id": 2, "product_id": 11, "quantity": 2, "price": 953 },
{ "id": 6, "order_id": 2, "product_id": 20, "quantity": 1, "price": 911 } ],
"name": { "id": 4, "name": "Product_4", ... "laravel_through_key": 2 }
如何使产品名称与 order_products 中的 product_id 对应?
这是我的表格图:
orders
id - integer
status - integer
order_products
id - integer
order_id - integer
product_id - integer
quantity - integer
price - integer
prods
id - integer
name - string
型号 订购
class Order extends Model
{
public function order_product()
{
return $this->hasMany('App\Order_product');
}
public function prod()
{
return $this->hasOneThrough('App\Prod', 'App\Order_product', 'order_id', 'id', 'id' );
}
模型产品
class Prod extends Model
{
public function order()
{
return $this->hasMany('App\Order', 'order_products');
}
модель Order_product
class Order_product extends Model
{
protected $fillable = ['order_id', 'product_id', 'quantity', 'price'];
}
资源订单
class Order extends JsonResource
{
public function toArray($request)
{
return [
'order_id' => $this->id,
'status' => $this->status,
'product_id' => $this->order_product,
'name' => $this->prod,
];
}
控制器顺序
class OrderController extends Controller
{
public function index()
{
$orders = Order::with(['order_product', 'prod'])->get();
return OrderResource::collection($orders);
}
}
犯罪嫌疑人X