Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Jeffxy's avatar

How to saveMany() if i need to add multiple relationship data?

As an example, i have 3 tables

$company = new Company();
.....
$company->save();

$data1 = new TableA([
........
]);

$company->saveMany($data1)

if I have a relationship on TableA and TableB to add? Is that mean that i need to create tableA data first? So means, I cannot use the above method to save my Table A data. I need a foreach() to loop and add TableA data then saveMany for the TableA relationship data.

Is it the only method to do it?

0 likes
4 replies
SilenceBringer's avatar

@jeffxy

if I have a relationship on TableA and TableB to add?

what kind of relatioships do you have? Show your migrations for both tables

Jeffxy's avatar

@SilenceBringer hasMany() relationship

Campaign has many tasks
Tasks has many contacts

So, my data creation will be campaign -> task -> contact. Create campaign and assign campaign_id to task, create task and assign task_id to contact.

SilenceBringer's avatar
Level 55

@Jeffxy as example

$campaign = Campaign::create([
	// your data here
]);

$task = $campaign->tasks()->create([
	// task data here
]);

$contract = $task->contracts()->create([
	// contract data here
]);

you can wrap task creation and contract creation into loop if you need to create many, like

$campaign = Campaign::create([
	// your data here
]);

foreach ($tasksData as $taskData) {
	$task = $campaign->tasks()->create($taskData);

	foreach ($contractsData as $contractData) {
		$contract = $task->contracts()->create($contractData);
	}
}
Jeffxy's avatar

@SilenceBringer If update also do the same right? Just change the create to update? Do i need specifically point it to an id or just include id in the data will do?

Please or to participate in this conversation.