Can somebody please help me, I’m losing my mind with this.
Below is the code I wrote that doesn’t work and I don’t know why. I always get “Call to a member function bindParam() on a non-object” error. For some reason construct gets called twice… What am I doing wrong? Thank you!
Database:
`id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
`applyDate` datetime NOT NULL,
`user` varchar(13) NOT NULL,
`start` time DEFAULT NULL,
`end` time DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `user` (`user`)
Controller:
public function actionIndex()
{
$model = new Period();
$this->render('index', array(
'model' => $model
));
}
Model:
private static $_instance = 0;
private $_cmdSelect;
public function __construct()
{
$user = 'username';
if (++self::$_instance == 1)
{
$sql = 'SELECT * FROM ' . $this->tableName() . ' WHERE user=:user LIMIT 1';
$this->_cmdSelect = Yii::app()->db->createCommand($sql);
}
$this->_cmdSelect->bindParam(':user', $user, PDO::PARAM_STR);
$this->attributes = $this->_cmdSelect->queryRow();
}
Model is created with gii with only construct method added on. Same with the controller.
I don’t know the other way how to create that, the proper way. I’ve found nothing about that neither on the forum nor in the definite guide tutorial. What I read that model gathers data, doesn’t it? Then what’s the right way to create a model with database or point me out where to look for it?
in this case you have static instance counter, but command is not static. so only first object created gets instance of command, following instances will see null…
I’m not sure what your overall goal is, but it seems to me that you should look into two things. First of all, consider overriding the init() method of model. It is called in the parent object (in this case I presume CActiveRecord) constructor. Init is normally the way you want to setup your specific model.
Second, it seems that you are trying to load a given username, which I assume you want the model to be populated with. Instead of using your constructor code, you could use the following from the controller (assuming your model is of class User):
BTW since the first generated instance of a class will become the class instance, _cmdSelect in your first approach should be available as self::model()->_cmdSelect. If you will try something like that again, as said, override init() instead of __construct().
Sorry for waiting that long to answer. As I understood, Active Record search is always put in a controller, isn’t it? But what about DAO and query builder? I understand how to write queries, but I don’t know where to put them and how to create and populate a model with them.