Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 Add model to hasMany relation in runtime

Tags:

php

yii2

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?

like image 562
Goover Avatar asked Dec 10 '25 16:12

Goover


1 Answers

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;
}
like image 170
Maarten van Middelaar Avatar answered Dec 13 '25 07:12

Maarten van Middelaar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!