How to insert multiple rows in laravel, need explanation - php

I want to insert multiple rows in a table, where the data collection I am inserting has a unique number. For example : I am inserting 2 row for a user_id number 1. My codes from controller is : I want to keep DB::table() instead of laravel eloquent
foreach($post_data['user_id'] as $key => $no){
$set_base = DB::table('package_user')
->Insert([
'base_id' => $post_data['base_id'],
'base_title' => $post_data['base_title'],
'user_id' => $no,
'package_id' => $post_data['package_id'],
'plan_id' => $post_data['plan_id'],
'currency' => $post_data['currency'],
'payable_plan_amount' => $post_data['total_amount'],
'created_at' => Carbon::now()
]);
}

Please refer How to insert multiple rows from a single query using eloquent/fluent there is a solution for both eloquent and querybuilder
$data = [
['user_id'=>'Coder 1', 'subject_id'=> 4096],
['user_id'=>'Coder 2', 'subject_id'=> 2048],
];
Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

You can also use fill() method if the model instance already created with the pre-defined populated datas.
<code>
$modelObj = new Model();
$modelCollection = collect($request->input())->all();
$modelObj->fill($modelCollection);
$modelObj->save();
</code>

Related

How to add value into existing array without replacing exists array data? [duplicate]

Here I used updateOrCreate method to post data but when I use this method old data replaced by new data but I want to add new data without updating or replacing exists data.
here is the code for insert data
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id], // match the row based on this array
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => json_encode($seat),
'price' => $request->price,
'profile' => 'pending',
]
);
I solved myself, I stored old data into $extSeat then merge with new data, I don't know the logic is correct or wrong but works
$extSeat = DB::table('bookings')->select('seat')->first();
$extSeat = explode(",", $extSeat->seat);
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id],// row to test if schedule id matches existing schedule id
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => implode(",", array_merge($seat,$extSeat )),
'price' => $request->price,
'profile' => 'pending',
]);

How to insert new data into exists row without replace exists data in laravel?

Here I used updateOrCreate method to post data but when I use this method old data replaced by new data but I want to add new data without updating or replacing exists data.
here is the code for insert data
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id], // match the row based on this array
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => json_encode($seat),
'price' => $request->price,
'profile' => 'pending',
]
);
I solved myself, I stored old data into $extSeat then merge with new data, I don't know the logic is correct or wrong but works
$extSeat = DB::table('bookings')->select('seat')->first();
$extSeat = explode(",", $extSeat->seat);
$booking = Bookings::updateOrCreate(
['schedules_id' => $schedules_id],// row to test if schedule id matches existing schedule id
[ // update this columns
'buses_id' => $buses_id,
'routes_id' => $routes_id,
'seat' => implode(",", array_merge($seat,$extSeat )),
'price' => $request->price,
'profile' => 'pending',
]);

Yii2 Query class does not return additional columns

I've got something like this
$query = Customer::find()
->select(['customer.name', 'surname', 'cityName' => 'cities.name', 'streetName' => 'streets.name'])
->joinWith(['city', 'street'])
->where(['group_id' => $id]);
When i do
return $query->all();
it returns only columns from customer table, but when i do something like this
$raw = $query->createCommand()->getRawSql();
return \Yii::$app->user_db->createCommand($raw)->queryAll();
it returns me all 4 columns. Why orm fails?
I'm using custom db connection (user), dynamicly connected after authorization. Anyway ActiveRecord->getDb() has been customized too and it works well till now.
it returns only columns from customer table, but when i do something like this.
Yes, that's right. Because Yii2 AR(Active Record) is ORM pattern. And it's try to return all result off query like object.
So, I will not tell the theory, I'd better suggest a solution variant:
$query = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->asArray()
->all();
return $query;
It's from Yii2 docs(performance tuning).
The result will be like:
[
all data selected from "customer",
['city' => all data selected from city joinWith],
['street' => all data selected from street joinWith]
]
I think, this is exactly what you need.
But, if you need objects. You can try marge objects to only one array.
$customer = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->all();
return [
'customer' => $customer,
'city' => $customer->city,
'street' => $customer->street,
];
you are using
->select(['customer.name', 'surname', 'cityName' => 'cities.name', 'streetName' => 'streets.name'])
so you will get selected columns only.
use,
$query = Customer::find()
->joinWith(['city', 'street'])
->where(['group_id' => $id])
->all();
this will give you all the columns

Convert an array to eloquent model in Laravel

I have mysql table 'test' with three columns,
1.sno 2.name 4.country
this code is easily understandable
$person = \App\Test::find(1);
$person->country; //Defined in Test eloquent model
now i want to do something like this:
$p = ['sno' => 1, 'name' => 'Joe', 'country' => '1' ];
$p->country; //Return relevent column form countries table as defined in Model
The thing to remember is that the user i am trying to map is already present in the database table. How to i convert an array to eloquent model?
You could instantiate the model class with no attributes:
$dummy = new \App\Test;
Then you can call the newInstance() method:
$attributes = ['sno' => 1, 'name' => 'Joe', 'country' => '1' ];
$desiredResult = $dummy->newInstance($attributes, true);
The true flag in the method is telling eloquent that the instance already exists in database, so you can continue working with it normally. Now you can do:
$desiredResult->country //'1'

Mass Assignment Insert in Eloquent

In Laravel 5.1 I'm using mass assignment for inserts. But i want to learn how to bulk insert with Eloquent.
I need to insert sold products in order process.
Here is my data for insert.
foreach($cart['fields'] as $key => $product)
{
$orderDetailData[] = [
'order_id' => $orderData['order_id'],
'product_id' => $product['id'],
'quantity' => $product['total_quantity'],
'price' => floatval($product['wholesale_price']),
'vat' => $product['vat'],
'vat_value' => floatval($product['vat_value']),
'discount_ratio' => $product['discount_ratio'],
'discount' => floatval($product['discount_value']),
'total_amount' => floatval($product['total_amount']),
];
}
Here is my code for insert
(new OrderDetail)->create($orderDetailData);
I think this method doesn't support bulk insert.
In Laravel 5.1 Manuel i see this.
DB::table('table')->insert($orderDetailData);
What should i do for mass assignment for bulk insert ? Should i use previous one (DB facade)
Because i'm getting error (500 internal server error) with this code
(new OrderDetail)->create($orderDetailData);
To insert/creae using mass-assignment you may declare an array in your Eloquent model like this one:
protected $fillable = [
'order_id',
'product_id',
'quantity',
'more fields names here...'
];
Defined field names will be inserted. Check the documentation for more. Also you may use forceCreate method which allows mass-assignment.
Also, the 500 internal server error is not obvious about the specific error so find it out.
this is example you can make array of your data and can insert the same way here going on.
$data = array(
array(
'name'=>'Coder 1', 'rep'=>'4096',
'created_at'=>date('Y-m-d H:i:s'),
'modified_at'=> date('Y-m-d H:i:s')
),
array(
'name'=>'Coder 2', 'rep'=>'2048',
'created_at'=>date('Y-m-d H:i:s'),
'modified_at'=> date('Y-m-d H:i:s')
),
//...
);
YourModelName::create($data);
you can insert that way
$data = array(
array('name'=>'Coder 1', 'rep'=>'4096'),
array('name'=>'Coder 2', 'rep'=>'2048'),
//...
);
OrderDetail::insert($data);
also make fillable those fileds
protected $fillable = [
'name',
'rep_id',
];

Categories