簡體   English   中英

Yii2在運行時將模型添加到hasMany關系

[英]Yii2 Add model to hasMany relation in runtime

有什么方法可以將新對象添加到hasMany關系中,而無需從數據庫中獲取?

我的意思是,如果我有一個名為FileList的ActiveRecord,它具有以下關系和加法器功能:

public function getFiles()
{
    return $this->hasMany(File::className(), ['fileListId' => 'id']);
}

public function addFile()
{
    $file = new File([
        'fileListId' => $this->id
    ]);

    return $file;
}

盡管$file有實際模型,但當我嘗試訪問$fileList->files[0] ,它將再次從數據庫中請求。

Ofc,我曾嘗試進行如下分配: $this->files[] = new File(...)但它沒有用,因為未提供設置器。 即使我為此添加了新的二傳手,我也真的不知道該如何填充才能使其按預期工作。

有什么建議嗎?

如果您的模型有一個關系文件,或者即使沒有,則可以調用$ activeRecord-> populateRelation('files',$ fileModels)

參見: http : //www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#populateRelation()-detail

在您的情況下:

public function addFile()
{
    $file = new File([
        'fileListId' => $this->id
    ]);

    return $file;
}

可能成為

public function addFile()
{
    $files = [];
    $files[] = $file = new File([
        'fileListId' => $this->id
    ]);

    $this->populateRelation('files',$files);

    return $file;
}

您可以將由關系返回的ActiveRecord數組保存在新屬性(正常屬性,而不是db字段)中,並使用new屬性。

我認為這有點過時。 我不知道您的用例,但是(假設使用正常的Web應用程序)通常在完成表單發布的處理后,您應該進行重定向,以便用戶無法通過刷新頁面來重新發送表單。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM