在這個(gè)例子中,我得到了一個(gè)有效的數(shù)組,但是嵌套的數(shù)組有不一致的地方{ "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 }由于第一個(gè)訂單中有三個(gè)產(chǎn)品,在第二個(gè)訂單中我已經(jīng)得到“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 }如何使產(chǎn)品名稱與 order_products 中的 product_id 對(duì)應(yīng)?這是我的表格圖:ordersid - integerstatus - integerorder_productsid - integerorder_id - integerproduct_id - integerquantity - integerprice - integerprodsid - integername - string型號(hào) 訂購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' ); }模型產(chǎn)品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貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
根據(jù)您的數(shù)據(jù)庫設(shè)計(jì),它假設(shè)belongsToMany在訂單和產(chǎn)品之間。
訂購型號(hào)
public function products()
{
return $this->belongsToMany('App\Prod', 'Order_product', 'order_id','product_id');
}
產(chǎn)品型號(hào)
public function orders()
{
return $this->belongsToMany('App\Order', 'Order_product','product_id', 'order_id');
}
- 1 回答
- 0 關(guān)注
- 110 瀏覽
添加回答
舉報(bào)
0/150
提交
取消