I am having a problem inserting a record into database table with create
.
// insert as chunks
foreach (array_chunk($mainArr, 1000) as $chunk) {
UnassignedTask::insert($chunk);
}
// insert as chunks
foreach (array_chunk($matchUnmatchArr, 1000) as $chunk) {
ProductMatchUnmatch::insert($chunk);
}
// for now ... remove this later.. in development
$apiBody['status'] = "Completed";
$projectsResponse = $this->postRemoteData($this->apiBaseUrl, 'search/searchprojectsbyclientdatestatus/?limit=500&offset=0', $apiBody, 'POST');
$prjResArr = json_decode($projectsResponse, true);
$projects = $prjResArr['results'];
foreach($projects as $pjt) {
if($pjt['id'] != $reqId) {
continue;
}
$project = Project::where('project_id', intval($reqId))->first();
if (!$project) {
//dd($pjt);
Project::create([
'client_code' => $pjt['client_name'],
'project_id' => $pjt['id'],
'file_name' => $pjt['file_name'],
'total_records' => $pjt['total_records'],
'total_unique_products' => $pjt['total_unique_products'],
'uploaded_datetime' => $pjt['start_date'],
'created_at' => $created_at,
'updated_at' => $updated_at
]);
}
}
The issue is with Project::create
that the record is not being inserted.
Notice that before inserting into projects
, two other bulk insert
transactions are performed in different tables : UnassignedTask::insert()
and ProductMatchUnmatch:insert()
.
If I comment these, then Project::create
works.
But with these uncommented Project::create
is not working.
EDIT:
Project.php
class Project extends Model
{
protected $table = 'projects';
protected $fillable = ['client_code', 'project_id', 'file_name', 'total_records', 'total_unique_products', 'uploaded_datetime', 'created_at', 'updated_at'];
}
What am I missing?
You can create instances with Model::create(). It works the same way as make but it doesn't save it.
It is possible different ways: you can use the mass assignment without saving.
Please remember to set first the $fillable property in your model.
WAY #1 : using the method fill
$model = new YourModel;
$model->fill([
'field' => 'value',
'another_field' => 'another_value'
]);
$model->save();
WAY #2 : using the constructor
$model = new YourModel([
'field' => 'value',
'another_field' => 'another_value'
]);
$model->save();
WAY #3 : like your current code`
$model = YourModel::create([
'field' => 'value',
'another_field' => 'another_value'
]);
Try to use as object instead:
$obj = new \App\Project;
$obj->client_code = $pjt['client_name'];
$obj->project_id = $pjt['id'];
...
$obj->save();
first of all change your if statement block because first() does not return boolean. it returns object or null. so you should check for null
if(is_null($project))
{
// your create code
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.