簡體   English   中英

在 Laravel 中創建嵌套關系

[英]Create nested relationships in Laravel

我一直在嘗試發現目前是否可以執行以下操作。

基本上我有三個模型: CustomerInvoiceUnit Customer有一張Invoice ;一張Invoice有很多Unit )。

我想知道是否可以無縫地執行以下操作:

...

# Let's pretend that further up the code that
# Customer has all the properties set and now
# being saved in the database.

$Customer->save();

# This is currently trying set the values of
# 'units' to a non-existent table column in 
# 'invoices' table.

$Customer->invoice()->create([
    "units" => [
        [
            "name" => "Unit 1",
            "amount" => 999.99,
            "tax" => "20%",
            "type" => "+"
        ]
    ]
]);

如果您按照您描述的那樣在 model 中設置關系,那么您可以實現接近您所展示的內容。 像這樣的東西:

Customer

public function invoice()
{
    return $this->hasOne(Invoice::class);
}

Invoice

public function units()
{
    return $this->hasMany(Unit::class);
}

然后調用:

$customer->invoice()->units()->create([
            "name" => "Unit 1",
            "amount" => 999.99,
            "tax" => "20%",
            "type" => "+"
        ]);

應該管用。

如果您按照描述的那樣在 model 中設置關系,那么您可以實現它接近您所展示的內容。 像這樣:

顧客

public function invoice()
{
    return $this->hasOne(Invoice::class);
}

發票

public function units()
{
    return $this->hasMany(Unit::class);
}

然后調用:

$customer->invoice()->units()->create([
    "name" => "Unit 1",
    "amount" => 999.99,
    "tax" => "20%",
    "type" => "+"
]);

應該管用。

如果你先調用保存發票,那么你應該調用 $invoice->units()

$invoice = $customer->invoice()->create([
    "campany" => "Unit 1",
    "dat" => "2022-02-18"
]);

$invoice->units()->create([
    "name" => "Unit 1",
    "amount" => 999.99,
    "tax" => "20%",
    "type" => "+"
]);

... 而不是通過客戶來完成。 所以 $invoice = $customer->invoice()->create(...); 之前,然后添加單位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM