推进保存:命名约定


Propel Saving: naming convention

>我在 Propel 中变量的大小写时遇到问题

当前有效的代码:

$this->_variables = array('Alias' => 'aliasOne', 'LocationId' => 1);
$model = new Client();
$model->fromArray($this->_variables);
$model->save();

但是,由于我的 API 输出的格式,我希望代码是

$array = array('alias' => 'aliasOne', 'location_id' => 1);
$model = new Client();
$model->fromArray($array);
$model->save();

怎么可能?

由于方法的第二个参数,它已经由 Propel 处理fromArray()

$array = array('alias' => 'aliasOne', 'location_id' => 1);
$model = new Client();
$model->fromArray($array, BasePeer::TYPE_FIELDNAME);
$model->save();

请参阅此常量的定义,以及此处的其他常量:https://github.com/propelorm/Propel/blob/master/runtime/lib/util/BasePeer.php#L63

您可以在客户端模型中使用映射数组进行代理fromArray,以在lib/model/om/BaseClient.php中转换密钥:

public function myFromArray($arr, $keyType = BasePeer::TYPE_PHPNAME)
{
  $map = array(
    'alias'       => 'Alias',
    'location_id' => 'LocationId',
    // you can add more
  );
  $newArr = array();
  foreach ($arr as $key => $value)
  {
    // replace the key with the good one
    if (array_key_exists($key, $map))
    {
      $newArr[$map[$key]] = $value;
    }
    else
    {
      $newArr[$key] = $value;
    }
  }
  $this->fromArray($newArr, $keyType);
}