在这个例子中,我得到了一个有效的数组,但是嵌套的数组有不一致的地方{ "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 对应?这是我的表格图:ordersid - integerstatus - integerorder_productsid - integerorder_id - integerproduct_id - integerquantity - integerprice - integerprodsid - integername - 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_productclass 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); } }
1 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
根据您的数据库设计,它假设belongsToMany在订单和产品之间。
订购型号
public function products()
{
return $this->belongsToMany('App\Prod', 'Order_product', 'order_id','product_id');
}
产品型号
public function orders()
{
return $this->belongsToMany('App\Order', 'Order_product','product_id', 'order_id');
}
- 1 回答
- 0 关注
- 86 浏览
添加回答
举报
0/150
提交
取消