我对 Doctrine 版本 1.1.0 中列名的大小写有疑问。
我有一个定义如下的记录(实体):
abstract class BaseProductsXsell extends Doctrine_Record
{
public function setTableDefinition()
{
$this->setTableName('products_xsell');
$this->hasColumn('ID', 'integer', 4, array('type' => 'integer', 'length' => 4, 'primary' => true, 'autoincrement' => true));
$this->hasColumn('products_id', 'integer', 4, array('type' => 'integer', 'length' => 4, 'unsigned' => 1, 'default' => '1', 'notnull' => true));
// and so on...
}
}
在MySQL数据库表中,“ID”的列名也是大写的。 但是当我尝试在查询后获取列名时:
$query = Doctrine_Query::create()->select('m.*')->from("ProductsXsell m");
$collection = $query->execute();
$columns = $collection->getTable()->getColumnNames();
print_r($columns);
输出看起来像这样:
Array
(
[0] => id
[1] => products_id
...
)
我没有在任何地方设置 doctrine 连接的 case 属性,所以它应该是默认值 (Doctrine::CASE_NATURAL)。
这会导致以下错误:
Fatal error: Uncaught exception 'Doctrine_Record_UnknownPropertyException' with message 'Unknown record property / related component "id" on "ProductsXsell"' in /opt/hocatec/bin/libs/Doctrine/Doctrine/Record/Filter/Standard.php:55
Stack trace:
#0 /opt/hocatec/bin/libs/Doctrine/Doctrine/Record.php(1282): Doctrine_Record_Filter_Standard->filterGet(Object(ProductsXsell), 'id')
#1 /opt/hocatec/bin/libs/Doctrine/Doctrine/Record.php(1240): Doctrine_Record->_get('id', true)
#2 /opt/hocatec/bin/libs/Doctrine/Doctrine/Access.php(117): Doctrine_Record->get('id')
#3 /opt/hocatec/bin/models/HocaSync.php(368): Doctrine_Access->offsetGet('id')
最佳答案
您要从数据库中选择的字段名称必须与您在模型中定义的名称相同。区分大小写。
您可以阅读更多相关信息 here .第一部分讲“列”并解释。
One problem with database compatibility is that many databases differ in their behavior of how the result set of a query is returned. MySQL leaves the field names unchanged, which means if you issue a query of the form "SELECT myField FROM ..." then the result set will contain the field myField.
Unfortunately, this is just the way MySQL and some other databases do it. Postgres for example returns all field names in lowercase whilst Oracle returns all field names in uppercase. “So what? In what way does this influence me when using Doctrine?”, you may ask. Fortunately, you don’t have to bother about that issue at all.
Doctrine takes care of this problem transparently. That means if you define a derived Record class and define a field called myField you will always access it through $record->myField (or $record['myField'], whatever you prefer) no matter whether you’re using MySQL or Postgres or Oracle etc.
In short: You can name your fields however you want, using under_scores, camelCase or whatever you prefer.
NOTE: In Doctrine columns and column aliases are case sensitive. So when you are using columns in your DQL queries, the column/field names must match the case in your model definition.
关于php - Doctrine 1.1 中大写列名的奇怪行为导致异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12508487/