简体   繁体   English

我可以在 Laravel 中一次保存带有关系表的数据吗?

[英]Can I save data with relational table at a time in Laravel?

I have two tables Lead and Comment .我有两张表 Lead 和Comment The relation is given below:关系如下:

 public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

Working Code:工作代码:

DB::transaction(function () use ($lead, $comment) {
            $lead->save();
            $lead->comments()->save($comment);
        });

But, my question is can I do it in a single line code, means only one save method?但是,我的问题是我可以在单行代码中做到这一点,意味着只有一种保存方法吗?

You can use the push method to recursively save the model object and its relationship.可以使用push方式递归保存model object及其关系。 So you might want to do something like:因此,您可能想要执行以下操作:

DB::transaction(function () use ($lead, $comment) {
    $lead->fill([
        //some attributes to be updated.
    ]);
    $comment->fill(['lead_id' => $lead->id]);
    $lead->push();
});

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

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