Laravel更新或创建关系

6
我有一个项目模型,它拥有项目翻译,我收到一个请求,包含我正在更新的项目和该项目的翻译。
现在,其中一些翻译已经存在于数据库中(它们拥有自己的id),而另一些则是新的。有没有一种简洁的方法来处理这个问题?
伪代码如下:对于找到的每个翻译,请更新它的关联(如果存在),否则为此项目创建一条新记录。
以下是我的项目布局。
class Item extends Model
{
    protected $fillable = ['menu_id', 'parent_id', 'title', 'order', 'resource_link', 'html_class', 'is_blank'];

    public function translations()
    {
        return $this->hasMany(MenuItemTranslation::class, 'menu_item_id');
    }
}

这是ItemTranslation(项目翻译)

class ItemTranslation extends Model
{
    protected $table = 'item_translations';
    protected $fillable = ['menu_item_id', 'locale', 'name', 'order', 'description', 'link', 'is_online'];
}
1个回答

14
你可以在 translations() 关联上使用 updateOrCreate 方法。例如:
$item->translations()->updateOrCreate([
    'name' => $translation['name'],
    // Fields that should be used to find an existing record.
], [
    'description' => "New description",
    // Fields that should be updated.
]);

第一个参数是您希望Eloquent通过其进行查找的数据,而第二个参数是您希望进行更新的数据。

两个参数将用于在找不到现有翻译时创建新的翻译


我想这个需要放在一个foreach循环中,以便遍历我收到的请求中的翻译。谢谢。 - Miguel Stevens
有一个 createMany 方法(https://laravel.com/docs/5.7/eloquent-relationships#the-create-method),但似乎没有类似于 updateOrCreateMany 的方法。 - D Malan
@DelenaMalan 也许你正在寻找类似于 https://gist.github.com/tonila/26f6a82c4dbe63d93b22ac67eaee2d6d 的东西。 - Prafulla Kumar Sahu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接