亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么 hasOneThrough 會顯示不合適的數據?

為什么 hasOneThrough 會顯示不合適的數據?

PHP
手掌心 2022-10-28 10:21:35
在這個例子中,我得到了一個有效的數組,但是嵌套的數組有不一致的地方{ "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');

}


查看完整回答
反對 回復 2022-10-28
  • 1 回答
  • 0 關注
  • 111 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號