在Laravel中创建嵌套关系

时间:2019-10-01 08:16:48

标签: php 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" => "+"
        ]
    ]
]);

1 个答案:

答案 0 :(得分:2)

如果按照描述的方式在模型中设置关系,则可以按照所显示的方式实现它。像这样:

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" => "+"
        ]);

应该工作。