Reputation: 101
basically i have three tables,
sms_content, sms_content_cities, sms_content_categories,
sms_content has foregin key in both other tables. i want to save record in these tables at once. Like i want to save sms_content_id in other tables which are sms_content_cities and sms_content_categories.
Here is my code:
$model = new SmsContent();
$model->version = 0;
$model->sms_from = 1;
$model->sms_text = $inputs['sms_text'];
$date = strtotime($inputs['start_date']);
$startDate = date("Y-m-d H:i:s", $date);
$noteID = $date;
$model->start_date = $startDate;
$endDate = date("Y-m-d", strtotime($inputs['end_date']));
$model->end_date = $endDate;
$model->title_audio = (isset($inputs['title_audio'])) ? $inputs['title_audio'] : "";
$model->audio = (isset($inputs['audio'])) ? $inputs['audio'] : "";
$model->enabled = 1;
$model->ivr_enabled = 1;
$model->note_id = DB::raw($noteID);
$model->sort_order = 0;
$model->save();
this code is saving my in sms_content table , but i dont know how to save his values in other table, like i want to save sms_content "Id" in other tables as a foregin key.
Upvotes: 0
Views: 146
Reputation: 3951
You can access model properties as soon as you save them in your database. In order to update your other models with data an id you need, you can simply do something like this:
$model1 = new SmsContent();
$model1->version = 0;
$model1->sms_from = 1;
//... and so on
$model1->save();
$model2 = new Model2();
$model2->sms_content_id = $model1->id;
//... and so on
$model2->save();
$model3 = new Model3();
$model3->sms_content_id = $model1->id;
//... and so on
$model3->save();
Upvotes: 1
Reputation: 14559
As soon as you do $model->save()
, an id
is saved in the $model
collection. You can simply access it using $model->id
.
Try dd($model->id);
after save() statement.
Upvotes: 1
Reputation: 429
After creating a record in the database, you can access its id immediately like the following:
$model->id
Now as you can access it, just create a new object of other Model
and save it there.
Upvotes: 1