I already asked this question in the feature requests subforum without an answer.
Now i'm wondering if i'm just doing something wrong.
I have a model with an database field foo_id and a relation 'foo'. I set foo_id to a valid id which exists in the related table, but I can't access model->foo.
class z extends CActiveRecord {
public static function model($className=__CLASS__) {
return parent::model($className);
}
public function tableName() {
return 'zertifikat';
}
public function relations() {
return array(
'teilnehmer' => array(self::BELONGS_TO, 'teilnehmer','teilnehmer_id'),
);
}
}
$a = z::model();
$teilnehmer = teilnehmer::model()->find();
$a->teilnehmer_id = $teilnehmer->te_id;
echo $a->teilnehmer_id; // 1
echo $teilnehmer->te_id; // 1
echo $a->teilnehmer->te_id; // Trying to get property of non-object
You should not modify data in z::model(). It is mainly served as a finder instance. Also, it is not good practice to try to bring in related objects for a new record. Why not just do a find() with the FK value?
also does not reflect what is in the database, still I can access it.
I think this is a inconsistency ("->teilnehmer_id" saying there IS a related object, "->teilnehmer" saying there is NO related object) - either I should be able to access teilnehmer_id AND teilnehmer, or neither. As the latter of course is a bad idea, both should work.
I think of models as database-backed objects, not just as templates for rows in the database. For that reason I believe operations on them should work the same no matter if they are save()d or not.
Even after save(), the relation is not updated (note that that is indeed "what i have in the database"). I have to pull the object from the database again to see the changed relation.
If I unterstand corretly this only applies to belongs_to relations.
Current situation:
Problem 1: after creating new AR instance and setting foreign key -> related object cannot be accessed
Problem 2: after finding existing AR instance, accessing related object, changing foreign key and saving the record -> wrong related object is returned.
If the related object is not accessed before saving, then after saving the correct one is returned.
I think it would be a great improvement if at least problem 2 was fixed.
Then Yii fails to provide the expected behavior. Whenever a foreign key gets changed, the related object should be dropped and then reloaded accordingly.