Search code examples
yii2

Yii2: Why in the beforeDelete method, does the hasMany return a null?


I'm trying to delete related data that has a many-to-many relationship

My complex model:

/**
 * @return \yii\db\ActiveQuery
 */
public function getComplexDocument()
{
    return $this->hasMany(ComplexDocument::className(), ['complex_id' => 'id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getDocuments()
{
    return $this->hasMany(Documents::className(), ['id' => 'document_id'])
        ->via('complexDocument');
}

In beforeDelete I do the following:

public function beforeDelete()
{        
    foreach ($this->documents as $document){
        var_dump($document);
    }
    return parent::beforeDelete();
}

Deletion does not happen, I checked and all hasMany connections return NULL.

In debug I see the following


Solution

  • I did this way:

    public function delete()
    {
        foreach ($this->documents as $document){
            $document->delete();
        }
        return parent::delete(); // TODO: Change the autogenerated stub
    }
    

    Everything works, all related documents are deleted, but it seems strange to me. In fact, this should be in beforeDelete (), but why are not links returned and therefore not deleted, so it should be, or is it a shortage of the framework?