This class allows accessing DB tables in an AR-like fashion, without the need to create a class for each table.
Usage ¶
Copy class to your project (eg to protected/components). Create a new instance by specifying table name:
$userModel = DynamicActiveRecord::forTable('user');
And then use it like any other AR class:
//list existing users
foreach ($userModel->findAll() as $user)
echo $user->id . ': ' . $user->name . '<br>';
//add new user
$userModel->name = 'Pavle Predic';
$userModel->save();
Download ¶
https://github.com/pavlepredic/Yii-dynamic-active-record</a>
nice, but what about "rules", "relations", etc?
you cannot use 'massive assignements', validation, relations, and stuff like that... They are configured in separate functions of each model definition, and this is it's all about with ActiveRecord...
@redguy
Yes, you do lose a lot of AR functionality. But the idea behind this class is that sometimes you simply need to perform a basic read/write on a table and it doesn't warrant creating a whole new class for it. If you need validation, relations etc. then use the good old way. To be honest, I'm not entirely sure what this class is good for. I wrote it simply because someone on Yii forum was asking if this was possible in Yii and I guess this proves that: Yes It Is ;)
@ I'm not entirely sure what this class is good for. good for manymany relation delete
in many many relations . if our database don't support the cascade deletion , we will have to delete the connection manually by ourselves . the better way is that generate a ActiveRecord for the bridge table . then
// afterDelete of the models which connected to each others , both side is ok ConnectionTable::model()->deleteAllByAttributes(array('model_id' => $model->id));
but it seems the ConnectionTable is only useful in such scenario (or you manually construct the connection)! so dynamicActiveRecord come here !
Automatic Rules
I create code for dynamic rules
this automatic rules from table schema, and check in field is allow null or not
/** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. $columns = Yii::app()->db->schema->tables[$this->_tableName]->columns; foreach ($columns as $column => $schema) { if (!$schema->allowNull) { $tmp_columns[] = $column; } } $col = implode(',',$tmp_columns); //var_dump($columns); return array( array($col,'required') ); }
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.