Import action afterCreate / afterSave not working to get parent ID

I need to create relationship data after the model created new data. But it doesn't work when I use afterCreate / afterSave, target_id is null in rate_card table.
class SiteFullImporter extends Importer
{
public function resolveRecord(): ?Target
{
return Target::firstOrNew([
'name' => $this->data['name'],
'address' => $this->data['address'],
'format' => $this->data['format'],
'size' => $this->data['size'],
'total_unit' => $this->data['total_unit'],
'estimate_traffic_per_month' => $this->data['estimate_traffic_per_month'],
'latitude' => $this->data['latitude'],
'longitude' => $this->data['longitude'],
]);
}

protected function afterCreate(): void
{
$this->record->rate_card()->create([
'rate_card_1_month' => 0,
'rate_card_3_months' => 0,
'rate_card_6_months' => 0,
'rate_card_12_months' => 0,
]);
}
class SiteFullImporter extends Importer
{
public function resolveRecord(): ?Target
{
return Target::firstOrNew([
'name' => $this->data['name'],
'address' => $this->data['address'],
'format' => $this->data['format'],
'size' => $this->data['size'],
'total_unit' => $this->data['total_unit'],
'estimate_traffic_per_month' => $this->data['estimate_traffic_per_month'],
'latitude' => $this->data['latitude'],
'longitude' => $this->data['longitude'],
]);
}

protected function afterCreate(): void
{
$this->record->rate_card()->create([
'rate_card_1_month' => 0,
'rate_card_3_months' => 0,
'rate_card_6_months' => 0,
'rate_card_12_months' => 0,
]);
}
The result in rate_card table :
| target_id | rate_card_1_month | rate_card_3_months | rate_card_6_months | rate_card_12_months |
|---|---|---|---|---|
| null | 0 | 0 | 0 | 0 |
| target_id | rate_card_1_month | rate_card_3_months | rate_card_6_months | rate_card_12_months |
|---|---|---|---|---|
| null | 0 | 0 | 0 | 0 |
1 Reply
minami
minamiOP3w ago
I found the answer. for someone out there who might need it. when we want to add data via the relationship name it will fail :
$this->record->rate_card()->create([]);
$this->record->rate_card()->create([]);
only can add via model directly :
protected function afterCreate(): void
{
RateCard::create([
'target_id' => $this->record->id,
]);
}
protected function afterCreate(): void
{
RateCard::create([
'target_id' => $this->record->id,
]);
}

Did you find this page helpful?