doctrine default values and relations

巧了我就是萌 提交于 2019-12-24 07:39:12

问题


In mysql I can set default value for column like this:

ALTER TABLE <Table> CHANGE <Column> DEFAULT <NEW_DEFAULT_VALUE>

I can retrieve default value:

SELECT DEFAULT(<Column>) FROM <Table> LIMIT 1

Is it possible to achieve this concept with Doctrine?

What I actually need is such methods in my table class:

class UserTable extend Doctrine_Table {
    /* ... */

    /** 
     * @return Doctrine_Record
     */
    public function getDefaultProperty() {
        return ???;
    }
    public function setDefaultProperty($value) {
        /* $value can be either integer or Doctrine_Record */
    }
}

回答1:


Let's see if we can figure this out.

Line 567 of Record.php, part of the assignDefaultValues() method which populates defaults as the object is created, says:

$default = $this->_table->getDefaultValueOf($column);

So you don't actually need to add a getDefaultProperty(), you can use:

$userTable = Doctrine::getTable('User');
$defaultName = $userTable->getDefaultValueOf('name');

However, you seem to want getDefaultProperty() to return a Doctrine_Record. If you just want to get back a whole object that has all the default values set on it, I'm pretty sure you can just use:

$defaultUser = new User(); (See the Doctrine manual for Default Values)

But be sure that your defaults are defined in the schema.yml, not just in the database. Doctrine won't read defaults out of the database, and relies on the schema to tell it what to do.

Let me know how that works.

Cheers, ~J




回答2:


The Doctrine_Table class contains the getDefaultValueOf method which does what you're looking for. So, if you have a doctrine record, you can write something like: $record->getTable()->getDefaultValueOf('address_line_1'); where 'address_line_1' is a column. Hope this helps.



来源:https://stackoverflow.com/questions/2939680/doctrine-default-values-and-relations

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!