This forum has moved to a new location and is in read-only mode. Please visit talk.octobercms.com to access the new location.
Hi all,
I would like to insert some data into a database table but would like some help on finding if the data already exist in the database table. if exist, then i would ignore them. I know of the php way of doing but i would to know the october cms/laravel way of doing it. Thanks in advance.
You may want the firstOrCreate
method. See the documentation for more details.
// Retrieve the flight by the attributes, otherwise create it
$flight = Flight::firstOrCreate(['name' => 'Flight 10']);
Note that the firstOrCreate
and firstOrNew
methods can be badly inefficient when dealing with a large number of records or huge data sets. MySQL has a solution with INSERT ... ON DUPLICATE KEY UPDATE
or UPDATE ... WHERE EXISTS
however these utilities are not available in the framework's database driver natively.
Here is some sample code that can be used for dealing with a large dataset to insert in to the database:
// The large dataset of items to insert
$data = [
'key1' => [...],
'key2' => [...],
];
// IDs that have already been found
$ids = [];
// Chunk over the database 250 records at a time
Db::table('acme_blog_table')
->select('id', 'key')
->chunk(250, function($records) use (&$data, &$ids) {
foreach ($records as $record) {
// Record not found in the large data set
if (!isset($data[$record->key])) {
continue;
}
// Record found, add to the existing IDs
$ids[] = $record->id;
// Remove from the large data set
unset($data[$record->key]);
}
})
;
// Create the remaining records
foreach ($data as $key => $attributes) {
$ids[] = Model::insertGetId($attributes);
}
// This variable now contains the IDs of all items
dd($ids);
Last updated
1-3 of 3