[英]Laravel relationships - pulling in ID's from multiple models
我有一個表結構如下:
創建包條目時,我想執行以下操作:
$shipment = $order->shipments()->create($request->all());
$package = $shipment->packages()->create();
如果我在$ shipment上丟掉骰子,那么里面有所有正確的ID,我希望這種關系可以創建它。 但是,如果沒有order_id值(訂單表中的id),則創建包裝失敗
我在誤解在這里應該如何雄辯嗎?
編輯:
命令
Schema::create('orders', function (Blueprint $table) {
$table->uuid('id');
$table->uuid('company_id');
$table->uuid('order_address_id');
$table->integer('user_id');
$table->string('unique_id');
$table->string('order_ref')->default('');
$table->string('status');
$table->boolean('hold_or_cancel')->default(0);
$table->string('shipping_method');
$table->dateTime('completed_at')->nullable();
$table->timestamps();
$table->unique(array('company_id', 'unique_id'));
出貨量
Schema::create('shipments', function (Blueprint $table) {
$table->uuid('id');
$table->uuid('order_id');
$table->uuid('company_id');
$table->string('status')->default('new');
$table->string('shipment_type');
$table->string('shipping_method')->default('');
$table->string('reference')->default('');
$table->timestamps();
});
包
Schema::create('shipment_packages', function (Blueprint $table) {
$table->uuid('id');
$table->uuid('order_id');
$table->uuid('company_id');
$table->uuid('shipment_id');
$table->string('tracking_number')->default('');
$table->integer('package_weight_g')->nullable();
$table->integer('package_length_cm')->nullable();
$table->integer('package_width_cm')->nullable();
$table->integer('package_height_cm')->nullable();
$table->timestamps();
});
要創建訂單,我使用以下方法可以正常工作。
$address = OrderAddress::create($data);
$order = $address->order()->create($data);
要創建貨運和包裹,我嘗試使用:
DB::transaction(function () use ($order, $request) {
$shipment = $order->shipments()->create($request->all());
$package = $shipment->shipmentPackages()->create();
});
但是,我無法使用此方法來瀏覽公司或訂單ID,以便輕松查看屬於訂單或公司的貨件和包裹列表,即貨件屬於訂單和公司。 對於裝運包裹,這屬於裝運,訂單和公司。
反思一下,也許我正在嘗試將每個表與太多事物相關聯。 我這樣做的理由是“如果我想找出某公司已發貨的所有包裹,那么我應該在包裹表中包括company_id”。 但是,最好僅查看公司擁有哪些貨運並從那里運出包裹。
看來您的關系是錯誤的,order_id應該在出貨表中,所以它與訂單上的ID有關。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.