I am using jenssegers package in Laravel 5 for mongodb.
I am inserting multiple data in below described way and data is inserted successfully in mongodb but then it through error before the script completes.
$AllTrans=array();
$AllTrans[]=array("InvoiceID"=>1,"Amount"=>50);
$AllTrans[]=array("InvoiceID"=>2,"Amount"=>150);
$mongo_connnection->collection('invoices')->insert($AllTrans);
Here is the error:
MongoException in Collection.php line 42:
No write ops were included in the batch
But i can not figure out problem, I have tried passing option like array('multi' => true) with insert query but it was not working.
It will work great with bulk addition, this way, you just need to create on array and pass it to it.
$temp = [
[
'item'=> "envelopes"
],
[
'item'=> "envelopesas"
],
[
'item'=> "lala"
]
];
$userData = DB::table('log')->raw( function ( $collection ) use ($temp) {
return $collection->insertMany($temp);
});
Related
I am new to laravel.
I have an issue when I am trying to update or create record in DB.
I have a table called DspAccountFee with this columns:
I want to create record of dsp_account_id + screen_type when the combination not exists, and to update if the combination exists.
this is my code: (just tried to update the first row keys of -> dsp_account_id(5187) + screen type (ctv). However nothing changed.
DspAccountFee::updateOrCreate(
['dsp_account_id' => $dsp_account_id, 'screen_type' => 'ctv'],
['pmp_percent' =>$fields['fee_ctv_pmp_percent'], 'omp_percent' => $fields['fee_ctv_omp_percent']]
);
When I print the values before the DB operation they exists:
\Log::info("dsp_account:");
\Log::info($dsp_account_id);
\Log::info("ctv pmp percent:");
\Log::info($fields['fee_ctv_pmp_percent']);
\Log::info("ctv omp percent:");
\Log::info($fields['fee_ctv_omp_percent']);
\Log::info("app pmp percent:");
What I am missing why it is not update the db? Nothing in logs and No exception
this is my method in the model
protected $fillable = array(
'dsp_account_id', 'screen_type'
);
Check the corresponding model and make sure that those columns exist in the
$fillable property. It should look somewhat like this.
protected $fillable = [
'dsp_account_id',
'screen_type',
'pmp_percent',
'omp_percent'
];
Your updateOrCreate syntax looks okay.
To update the updated_at column in your database, you can use the touch() method: you'll need to edit your code to something like this
$foo = DspAccountFee::updateOrCreate([
'dsp_account_id' => $dsp_account_id,
'screen_type' => 'ctv'
],
[
'pmp_percent' => $fields['fee_ctv_pmp_percent'],
'omp_percent' => $fields['fee_ctv_omp_percent']
]);
$foo->touch();
In my MongoDB collection, all documents contain a mileage field which currently is a string. Using PHP, I'd like to add a second field which contains the same content, but as an integer value. Questions like How to change the type of a field? contain custom MongoDB code which I don't want to run using PHP, and questions like mongodb php Strings to float values retrieve all documents and loop over them.
Is there any way to use \MongoDB\Operation\UpdateMany for this, as this would put all the work to the database level? I've already tried this for static values (like: add the same string to all documents), but struggle with getting the data to be inserted from the collection itself.
Some further hints:
I'm looking for a pure PHP solution that does not rely on any binary to be called using exec. This should avoid installing more packages than needed on the PHP server
Currently, I have to use MongoDB in v4.0. Yes, that's not the most recent version, but I'm not in the position to perform an upgrade
Try this, please:
01) MongoDB Aggregate reference:
db.collectionName.aggregate(
[
{ "$addFields": {
"intField": { "$toInt": "$stringFieldName" }
}},
{ "$out": "collectionName" }
]
)
02) Possible PHP solution (Using as reference https://www.php.net/manual/en/mongocollection.aggregate.php):
$pipeline = array(
array(
'$addFields' => array(
'integerField' => array('$toInt' => '$mileage')
)
),
array(
'$out' => 'collection'
),
);
$updateResult = $collection->aggregate(pipeline);
You could use $set like this in 4.2 which supports aggregation pipeline in update.
$set stage creates a mileageasint based on the previous with $toInt value
db.collection.updateMany(
<query>,
[{ $set: { "mileageasint":{"$toInt":"$mileage" }}}],
...
)
Php Solution ( Using example from here)
$updateResult = $collection->updateMany(
[],
[['$set' => [ 'mileageasint' => [ '$toInt' => '$mileage']]]]
);
Laravel Framework 5.4.36 | psql (PostgreSQL) 11.2
Hi, now I want to migrate my existing Laravel project DB from MySQL into PostgreSQL, I have some trouble here
$insert = [
"a" => "name",
"b" => age
.
.
];
return DB::table('table')->insert($insert);
when I try to insert DB with array data it returns like this,
Undefined column: 7 ERROR: column "0" of relation "table" does not exist ..
LINE 1: insert into "table" ("0", "1", "2", ..
it not return "a","b","c".. column but array position. with MySQL DB it is working
and
i try to get last inserted data id like this,
$data = [
'name'=>$name,
'address'=>$address,
'id_class'=>$id_class,
'lat'=>$lat,
'long'=>$long,
'is_changed'=>true
];
return Model::create($data)->id;
this will return undefine for id value
i update my code, 1st problem already resolved with this:
$insert[] = [
"a" => "name",
"b" => age
.
.
];
foreach(array_chunk($insert,5000) as $i){
return DB::table('table')->insert($insert);
}
I once got the same error.
The issue was
Accidentally i put
DB::beginTransaction();
In my auth middleware, forgot to close the beginTransaction by
DB::commit();
that is why, every time i try to insert new value, i get the ID but entry doesn't appear in database.
I am using Laravel 5.5 and I am declaring my model object the following:
$product = new product();
$product->name = $coinArr[$key];
$product->symbol = $symbolArr[$key];
$product->current_price = $priceArr[$key];
///save image to public folder
$fileName = basename($imgArr[$key]);
Image::make($imgArr[$key])->save(public_path('images/' . $fileName));
$product->asset_logo = $fileName;
//$product->updateOrCreate();
App/Product::updateOrCreate($product);
If the product does not exist in the database I would like to create it else just update it.
I tried the following two ways to use the updateOrCreate method. However, I receive the following error for App/Product::updateOrCreate($product);:
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::updateOrCreate(), 0 passed in C:\Users\admin\Desktop\Coding Projects\laravel_proj\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php on line 1455 and at least 1 expected
And the following error for $product->updateOrCreate();:
Type error: Too few arguments to function Illuminate\Database\Eloquent\Builder::updateOrCreate()
Any suggestions how to use updateOrCreate with my model object?
I appreciate your replies!
When you use updateOrCreate, you need to choose which attributes are used to determine if the product exists already. The function takes 2 arrays:
product::updateOrCreate([
'name' => $coinArr[$key] //Laravel will check if this model exists by name
],[
'symbol' => $symbolArr[$key] //if exists, will update symbol. if doesnt exist, will create new with this name and symbol
]);
That's not how the updateOrCreate() method works. In the first parameter you put an array with search conditions. If you want to search existing route by name for example, the correct syntax will be:
Product::updateOrCreate(
[
'name' => $coinArr[$key]
],
[
'symbol' => $symbolArr[$key],
'current_price' => $symbolArr[$key],
'asset_logo' => $fileName
]
);
The second parameter is array for creating a new object.
https://laravel.com/docs/5.5/eloquent#other-creation-methods
I have a dynamic input field called name="step[]". When submitting the form and displaying the $request->step using dd, I get this:
array:3 [
0 => "Test Step 1"
1 => "Test Step 2"
2 => "Test Step 3"
]
So it is an array. Now, when I want to insert the data using:
$project = new Project;
$project->name = $request->name;
$project->save();
$project->steps()->saveMany($request->step);
I am getting this error:
Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, string given
Project Model:
public function steps()
{
return $this->hasMany('App\Step');
}
My goal is to create a new Project and save it to the database, and save all steps in my Step table. So each Project hasMany steps. Not sure why I am getting the above error though, since I am passing an array?
I usually realize using a foreach loop. Your relation method seems to look OK. Does this work?
foreach($request->steps as $step) {
$project->steps()->create(['step' => $step]);
}
Did you try using the attach method?
$project->steps()->attach($resquest->input('steps'));