简体   繁体   English

Laravel 更新有很多关系

[英]Laravel Update hasMany relation

I've got the following:我有以下几点:

MirrorModule Model镜像模块模型

/**
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function xous()
{
    return $this->hasMany('App\Models\Xou');
}

Xou model徐模型

public function mirrorModule()
{
    return $this->belongsTo('App\Models\MirrorModule');
}

Basic stuff here.基本的东西在这里。 All I want is update the just like the sync method in ManyToMany which takes id's and figures out the rest for you.我想要的只是更新就像 ManyToMany 中的同步方法一样,它需要id's并为您找出其余的。

I've got an array coming in looks like this:我有一个数组,看起来像这样:

在此处输入图片说明

What I have tried我试过的

   if ($request->has('xous')) {
            $arr = [];
            foreach ($data['xous'] as $value) {
            // $arr[] = [
            //     'id' => $value['id'],
            // ];
            // $arr[] = $value;
           $xous = Xou::findOrFail($value['id']);
          $mm = $mirrorModule->xous()->where('mirror_module_id',$mirrorModule['id'])->get(); 
          $mm->update() // ?? or save()  save returns error 

        }
    }

I also looked over this article to implement my own sync method, but can't get it work.我也查看了这篇文章来实现我自己的同步方法,但无法让它工作。

Any ideas?有任何想法吗? Other approaches are welcome as well.其他方法也是受欢迎的。

Use whereIn on an array of ids:在 id 数组上使用whereIn

$ids = array_map(function ($item) {
    return $item['id']:
}, $request->get('xous'));

$mirrorModule->xous()->whereIn('id', $ids)->update(...);

You're calling ->update() on Collection object, ->get() returns a Collection object, not a model or a query.您正在对 Collection 对象调用->update()->get()返回一个 Collection 对象,而不是模型或查询。

What you need to do (if I understood correctly what you want) is你需要做的(如果我理解正确的话)是

 if ($request->has('xous')) {
        $arr = [];
        foreach ($data['xous'] as $value) {
        // $arr[] = [
        //     'id' => $value['id'],
        // ];
        // $arr[] = $value;
       $xous = Xou::findOrFail($value['id']);
       $mm = $mirrorModule->xous()->where('mirror_module_id',$mirrorModule['id'])->update([
           'attribute_to_update' => 'some_value'
       ]); 

    }
}

which will basically update all rows in database with that mirror_module_id with some value.这将基本上使用具有某个值的mirror_module_id更新数据库中的所有行。

Please, avoid executing queries within the loop.请避免在循环内执行查询。 findOrFail accepts array of ids, so you can extract ids to temp variable, and then do bulk update. findOrFail 接受 id 数组,因此您可以将 id 提取到临时变量,然后进行批量更新。 Update method accepts array of arguments you want to change (update). Update 方法接受要更改(更新)的参数数组。

您可以按照以下方式操作:

 $category->posts()->update(['category_id' => $newCatId]);

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

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