I would like to know how to save relationships in yii2. I have 3 models and my view show the Virtual Invoice with same invoice info and all the incomes.
INCOME (Model)
class Income extends \yii\db\ActiveRecord
{
public function getInvoice()
{
return $this->hasOne(Invoice::className(), ['id' => 'invoice_id']);
}
}
INVOICE (Model)
class Invoice extends \yii\db\ActiveRecord
{
public function getIncomes()
{
return $this->hasMany(Income::className(), ['invoice_id' => 'id']);
}
public function getVirtualInvoice()
{
return $this->hasOne(VirtualInvoice::className(), ['invoice_id' => 'id']);
}
}
Virtual INVOICE (Model)
class VirtualInvoice extends \yii\db\ActiveRecord
{
public function getInvoice()
{
return $this->hasOne(Invoice::className(), ['id' => 'invoice_id']);
}
}
In the controller I to get the incomes, for example:
$incomes = Income::find()->where([‘id’ =>$_POST[“selectedIds”]])->all()); // Array of ActiveRecords
I get the invoice data:
$invoice = new Invoice();
$invoice->invoice_date = date(‘Y-m-d’);
$invoice->total_amount = $total;
And the Virtual invoice data:
$virtualInvoice = new VirtualInvoice();
$virtualInvoice->number = 1234; //TODO
Could i save the relations like yii 1.1 ? The example below failed because the property is read-only
$virtualInvoice->invoice->incomes = $incomes
$virtualInvoice->invoice = $invoice;
$virtualInvoice->save();
If I try to do a link after save only the invoice, failed showing this message (Call to a member function isPrimaryKey() on a non-object)
$invoice->link(‘incomes’, Income::find()->where([‘id’ => [1,2,3]])->all());
The only solution that i find is saving with php transaction: First Invoce, then incomes with $invoice->getPrimaryKey() and finally virtual invoice with $invoice->getPrimaryKey() too.
I think i could use afterSave and beforeSave in VirtualInvoice and Invoice class but I have to check $_POST data in Model and i don´t like it.
Somebody has this problem?
Thanks.