【问题标题】:Save two new models with a relationship to each other at once in Laravel 6在 Laravel 6 中一次保存两个相互关联的新模型
【发布时间】:2019-10-03 09:22:34
【问题描述】:

我想知道同时保存两个相互关联的不同模型的最佳方法是什么。假设我有一个 Subscription 模型和一个 Participant 模型,当我创建一个 Participant 时,它必须创建一个 Subscription 并将 Participant 链接到它。

例子:

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

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

保存:

$s = new App\Subscription();

$p = new App\Participant();

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

但是订阅没有保存。任何想法保存它们的最佳做法是什么,检查它们是否已保存并建立关系?

【问题讨论】:

  • 为什么要“同时”保存它们?你不能$s->save; $s->participants()->save($p);吗?
  • 是的,我可以!但是,当转到下一行时,保存功能是否总是完成?而当参与者的保存失败时,我将如何处理订阅模型?
  • 啊,我明白你的意思了。我会回复的

标签: laravel eloquent laravel-6 eloquent-relationship


【解决方案1】:

您正在寻找的是交易。你可以用两种方法来做。

使用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);
});

或手动,您可以控制何时提交或回滚。

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

【讨论】:

  • 哇!不知道这存在。使用手动方法,我可以显示错误。非常感谢!
【解决方案2】:

您可以通过交易来做到这一点(如@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();
    }
}

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-31
    • 1970-01-01
    • 1970-01-01
    • 2018-12-11
    相关资源
    最近更新 更多