Создать вложенные отношения в Laravel - PullRequest
0 голосов
/ 01 октября 2019

Я пытался выяснить, возможно ли в настоящее время сделать следующее.

В основном у меня есть три модели: Customer, Invoice и Unit. (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 Ответ

2 голосов
/ 01 октября 2019

Если вы настроите отношения в модели так, как вы их описали, тогда вы сможете добиться этого близко к тому, что вы показали. Примерно так:

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

Должно работать.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...