简体   繁体   English

在 Laravel 6 中一次保存两个相互关联的新模型

[英]Save two new models with a relationship to each other at once in Laravel 6

I'm wondering what's the best way to save two different models with a relationship to each other at once.我想知道同时保存两个相互关联的不同模型的最佳方法是什么。 Consider I have a Subscription model and a Participant model, and when I create a Participant, it has to create a Subscription and link the Participant to it.考虑我有一个订阅 model 和一个参与者 model,当我创建一个参与者时,它必须创建一个订阅并将参与者链接到它。

Example:例子:

class Subscription extends Model
{
    public function participants()
    {
        return $this->hasMany('App\Participant');
    }
}

class Participant extends Model
{
    public function subscription()
    {
        return $this->belongsTo('App\Subscription');
    }
}

Saving:保存:

$s = new App\Subscription();

$p = new App\Participant();

$s->participants()->save($p);

But then the Subscription isn't saved.但是订阅没有保存。 Any ideas what's the best practice to save them both, check if they're saved and make the relation?任何想法保存它们的最佳做法是什么,检查它们是否被保存并建立关系?

What you're looking for is transactions.您正在寻找的是交易。 You can do them 2 ways.你可以用两种方法来做。

Using DB::transaction() and putting everything in a Closure使用DB::transaction()并将所有内容放在一个闭包中

use DB;

$s = new App\Subscription();
$p = new App\Participant();

DB::transaction(function () use ($s, $p) {
    // If something fails, it will rollBack, if not, it will commit.
    $s->save();
    $s->participants()->save($p);
});

Or manually, where you control when it's commited or rollback'd.或者手动,您可以控制何时提交或回滚。

use DB;

$s = new App\Subscription();
$p = new App\Participant();

try {
    DB::beginTransaction();
    $s->save();
    $s->participants()->save($p);
    DB::commit();
} catch (\Exception $e) {
    DB::rollBack();
}

More info on transactions有关交易的更多信息

You can do that with transactions (as in @IGP's answer), or just add saving line for subscriptions too..您可以通过交易来做到这一点(如@IGP 的回答),或者也可以为订阅添加保存线..

public function test()
{
    // Begin Transaction
    DB::beginTransaction();

    try
    {
        $participant = new Participant();

        $subscription = new Subscription();
        // $subscription->name = "parent subscription"; // init necessary columns
        $subscription->save();

        $participant->subscription()->associate($subscription);
        // $participant->name = "child participant"; // init necessary columns
        $participant->save();

        // Commit Transaction
        DB::commit();

        // Continue your logic here

    } catch (\Exception $e) {
        // Rollback Transaction
        DB::rollback();

        return $e->getMessage();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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