在抽象类的Update方法中使用foreach循环将键值填充到模型中


Laravel mass assignment to model in Update method in abstract class using foreach loops to fill keys with values

如何创建属于抽象类的update()函数的泛型方法?确切地说,我希望它能够动态地生成数组$keys并与更新的$values链接,以便不同的存储库可以从这个抽象类中使用这个函数。

public function update($id, array $data)
{
    $related              = $this->modelClassInstance->find($id);
    $related->name        = $data['name'];
    $related->description = $data['description'];
    $related->started_at  = $data['started_at'];
    $related->ended_at    = $data['ended_at'];
    if($related->save()) {
      $response = MyResponse::error(201, true, 'Event sucessfully updated');
      return $response;
    } 
    else {
      $response = MyResponse::error(200, false, 'Event unsucessfully updated');
      return $response;
    }
}

我需要这样的东西

$data = array(1,2,3,4,5,6,7,8,9);
foreach($data as $key=>$value)
{
   .....
}

我的键是名称、描述、started_at和endd_at,但这意味着该函数是特定于模型的。我希望这个键是动态生成的,并从传递的数据中获得新的值。

for循环对于Laravel方法来说是不必要的,在进行了各种站点的研究之后,这些方法是相当可靠的。我想到了这个简单的解决办法

    public function update($id, array $data)
            {
                $related = $this->modelClassInstance->find($id);
                $related->fill($data);
                if($related->save()) 
                {
                    $response = MyResponse::error(201, true, 'Event sucessfully updated');
                    return $response;
                } 
                else 
                {
                    $response = MyResponse::error(200, false, 'Event unsucessfully updated');
                    return $response;
                }
            }

这是fill()方法在Laravel Eloquent Model中的实现方式,如果你想寻找类似的实现方法,请参考

public function fill(array $attributes)
    {
        $totallyGuarded = $this->totallyGuarded();
        foreach ($this->fillableFromArray($attributes) as $key => $value)
        {
            $key = $this->removeTableFromKey($key);
            // The developers may choose to place some attributes in the "fillable"
            // array, which means only those attributes may be set through mass
            // assignment to the model, and all others will just be ignored.
            if ($this->isFillable($key))
            {
                $this->setAttribute($key, $value);
            }
            elseif ($totallyGuarded)
            {
                throw new MassAssignmentException($key);
            }
        }
        return $this;
    }