dqwh1119 2019-03-12 08:49
浏览 462

Laravel更新或创建关系

I have an Item model, that has ItemTranslations, I'm receive a Request with the Item I'm updating and the translations for that Item.

Now some of those translations will already be in the database (they have their own id), and some of them will be new. Is there a clean way to go about this?

In pseudo: Update the Item with this request, for each Translations you find in this request, update the translation relation if it exists, else create it for this Item.

This is the layout of my Item.

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');
    }
}

This is the ItemTranslation

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

1条回答 默认 最新

  • duandi2853 2019-03-12 09:09
    关注

    You could use the updateOrCreate method on the translations() relationship. For example, $item->translations()->updateOrCreate(['name' => $translation['name'], ], [ < the rest of the translation's data> ]); Note, that the first argument to the updateOrCreate method should be the data you want to look up the translation by, i.e. data that would stay the same. The second argument should be the data that can be updated.

    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备