简体   繁体   中英

Create nested relationships in Laravel

I've been trying to discover whether or not it's currently possible to do the following.

Basically I have three models: Customer , Invoice , and Unit . ( Customer has one Invoice ; an Invoice has many Unit s).

I was wondering if it was possible to seamlessly do the following:

...

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

If you setup the relationships in the model as you described them, then you can achieve it close to what you've shown. Something like this:

Customer

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

Invoice

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

Then calling:

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

Should work.

If you setup the relationships in the model as you described them, then you can achieve it close to what you've shown. Something like this:

Customer

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

Invoice

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

Then calling:

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

Should work.

if you call save on the invoice first, then you should just call $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" => "+"
]);

... instead of doing it through the Customer. so $invoice = $customer->invoice()->create(...); before, and then add units.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM