【问题标题】:Laravel Update or Create RelationshipsLaravel 更新或创建关系
【发布时间】:2020-09-11 19:06:29
【问题描述】:

我有一个具有 ItemTranslations 的 Item 模型,我收到了一个请求,其中包含我正在更新的 Item 和该 Item 的翻译。

现在其中一些翻译已经在数据库中(它们有自己的 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'];
}

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    您可以在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.
    ]);
    

    first 参数是您希望 Eloquent 查找 translation by 的数据,second 参数是您希望 Eloquent 查找的数据想要更新

    两个参数将用于在找不到现有translation创建一个新的translation

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-13
    • 2014-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多