doumen5491 2015-10-06 07:41
浏览 36

Propel ORM - 在委托表的列上使用setByName

I'm using Propel ORM to make things easier in loading and saving a pretty large form to a database. The form is huge but it's pretty much flat data, so it's essentially one big table (lets call it persons) with a couple hundred columns. I don't want to have a couple hundred columns in one table so I have one master table and a bunch of one-to-one sub-tables.

I'm using the delegate behavior described here. This is nice because I can call PersonQuery::create()->findPK($id)->toArray() and it gives me not just the data in Person but also the data in every sub-table. I can then load this data into my form very easily.

When a user edits the form and submits it, I send the form data to the server using POST. I then iterate through that POST data in order to assign it to a person object and I use "setByName" to do this instead of the specific functions Propel provides. So instead of doing this:

   $person = PersonQuery::create()->findPK($id);
   $person->setAge($_POST['age']);
   $person->setName($_POST['name']);
   //repeat for hundreds of columns

I can just do this:

$person = PersonQuery::create()->findPK($id);
foreach($_POST as $field=>$value){
   //before you ask, yes, i validate $field here
   $person->setByName($field, $value);
}

The problem that I'm having is that this doesn't work for my delegate tables. So if I have my main table as Person, and I have a delegate table called Favorites, with a field Color, I can do $person->setColor('Blue'), but I can't do $person->setByName('Color','Blue').

So... is there anyway I can do the above or something similar? I really don't want to write out the setter for every column and have to update that list of setters whenever I change the database. Thanks!

  • 写回答

1条回答 默认 最新

  • douran9707 2015-10-30 17:50
    关注

    Perhaps you could have a lookup for fields.

    $lookup = array('color' => 'setColor');
    
    foreach ($_POST as $fieldName => $fieldValue) {
        if (isset($lookup[$fieldName])) {
            $func = $lookup[$fieldName];
            $person->$func($fieldValue);
        }
    }
    

    You don't need the lookup array, your function could be a concatenation of 'set' and ucwords($fieldName) = setColor

    I don't recommend this as it could potentially be unsafe without the lookup.

    评论

报告相同问题?