Is there any way to add new object to hasMany relation without refetching from DB?
I mean if I have an ActiveRecord named FileList which have the following relation and adder function:
public function getFiles()
{
return $this->hasMany(File::className(), ['fileListId' => 'id']);
}
public function addFile()
{
$file = new File([
'fileListId' => $this->id
]);
return $file;
}
Despite having the actual model in $file, when I try to access $fileList->files[0] it will be requested again from the DB.
Ofc, I've tried to make an assignment like: $this->files[] = new File(...) but it isn't working, because no setter is given. And even if I add new setter for this, I really don't know, what to fill in to make it work as expected.
Any suggestions on this?
If your model has a relation files, or even when it does not - you could call $activeRecord->populateRelation('files',$fileModels)
see: http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#populateRelation()-detail
In your case:
public function addFile()
{
$file = new File([
'fileListId' => $this->id
]);
return $file;
}
could perhaps become
public function addFile()
{
$files = [];
$files[] = $file = new File([
'fileListId' => $this->id
]);
$this->populateRelation('files',$files);
return $file;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With