I have a sensor list form in my program. There the user can do CRUD.
How do when the user enters new sensor data, the new data automatically creates a new column in the table in my database (automatically alter table)
public function store(Request $request){
$data = new Mst_sensor();
$arr = array_merge($arr, ['created_by' => Auth::user()->userid, 'created_at' => date('Y-m-d H:i:s')]);
$data->create($arr);
$sensor= new Trs_sensor_d;
$table = $sensor->getTable();
$columns = \DB::getSchemaBuilder()->getColumnListing($table);
$data_field = [];
foreach ($columns as $k => $v) {
$data_field[$k] = $v;
}
$removed = array_pop($data_field);
$fix_data_field = end($data_field);
$q = "ALTER TABLE `trs_raw_d_gpa` ADD `coba` VARCHAR(25) NULL AFTER '" . $fix_data_field . "'";
}
How can alter table run automatically???
Think about how to design the database so that users cannot change the structure.
What you want to do is not recommended.
Related
My data in database:
My objective is to retrieve all data of company collection (MongoDB) data from the database. The company collection holds one or many trucks. I have implemented one-to-many reference between company and trucks collection. That is working fine.
I am using query builder to get all the data. But, my code is not giving me all the Trucks of the specific company. It is retrieving only one truck name for specific documents.
My API code is checking the length of the truck's array and storing the name for the truck on ta[] array. Code is not written nicely as I have tried so many methods and I am frustrated now.
How can I retrieve my data?
My API:
/**
* #Route("/koco/get/company/query", name="queryToGetCompany")
* #Template()
*/
public function queryForCompanyAction()
{
$checkarray = array();
$dm = $this->get('doctrine_mongodb')->getManager();
$qb = $dm->createQueryBuilder(Company::class);
$qb->find(Company::class);
$query = $qb->getQuery();
$comapnies = $query->execute();
foreach ($comapnies as $company)
{
$objectId = $company->getId();
$objectName = $company->getName();
$objectAddress = $company->getAddress();
// for length
$len = count($company->getTrucks());
echo $len;
// For trucks
$Trucks = $company->getTrucks();
foreach ($Trucks as $truckname)
{
$ta = array();
for($i=0;$i< $len;$i++){
$object = new Truck();
$object = $truckname->getName();
$ta[] = $object;
}
}
$checkarray[] = array(
'Id' => $objectId,
'Name' =>$objectName,
'Address' =>$objectAddress,
'Trucks' => $ta,
);
}
$data = [
'Comapnies' => $checkarray,
];
return new JsonResponse($data);
}
My results from the API:
The 2nd and third companies are giving me the same records for the name of trucks, but in my database the truck names are different.
Your foreach and your for loop are colliding, in conjunction with your array being emptied inside the foreach loop. If you reset your array before the foreach loop, not inside, and also just use a foreach without the for, I think this is what you want.
What is happening in your code as presented in the question is that the array is wiped out between trucks, so you only get the last truck. Additionally, because of the manually counted for loop, the number of copies of the last truck is equal to the total number of trucks associated with each company.
This is my suggestion based on what you have shown, replacing the entire foreach loop with this code.
$ta = array();
foreach ($Trucks as $truckname)
{
$object = new Truck();
$object = $truckname->getName();
$ta[] = $object;
}
I have a project written using PHP on the top of Laravel 5.7. I am using Eloquent ORM to interact with the database.
I need to be able to update lots of records after pulling them from the database.
Here is how I am trying to do it.
$records = Record::where('Key','Test')->get();
$values = collecT([
['Id' => 1, 'Col' => 100],
['Id' => 2, 'Col' => 200],
['Id' => 3, 'Col' => 500],
....
]);
foreach($records as $record) {
$newValue = $values->where('Id', $record->id)->first();
if(is_null($newValue)){
continue;
}
$record->ColName = $newValue['Col'];
$record->save();
}
The above code does not write the updated value to the database. However, if I do the following it gets updated
foreach($values as $value) {
$record = Record::where('Key','Test')->where('id', $value['Id'])->first();
if(is_null($record)){
continue;
}
$record->ColName = $value['Col'];
$record->save();
}
Although the above code works, I have to make 1 select + 1 update statement for every record in the $values array. If the size of $values array is 1000. That's going to generate up to 2000 queries which are insane!
How can I correctly update multiple records in the database without doing range-update.
If all the rows you are trying to update would get the same value it is an easy problem. The problem becomes a bit more tricky because all your rows need to be updated with different values. This comment on a github issue of laravel has a solution that will do it with a single query, allowing him in that case with a 13x performance boost for 1000 rows to be updated compared to updating them one by one:
public static function updateValues(array $values)
{
$table = MyModel::getModel()->getTable();
$cases = [];
$ids = [];
$params = [];
foreach ($values as $id => $value) {
$id = (int) $id;
$cases[] = "WHEN {$id} then ?";
$params[] = $value;
$ids[] = $id;
}
$ids = implode(',', $ids);
$cases = implode(' ', $cases);
$params[] = Carbon::now();
return \DB::update("UPDATE `{$table}` SET `value` = CASE `id` {$cases} END, `updated_at` = ? WHERE `id` in ({$ids})", $params);
}
You can also try https://github.com/mavinoo/laravelBatch which does something similar.
I want to get the data form database table and create a new row in another table.
Which 1 PO have many PoProducts.
$_getPO = Order::find($id);
$_getPOProducts= OrderProducts::where('order_id', $id)->get();
$order_no = $_getPO->order_no;
$eta = $_getPO->eta;
$_Order = new DeliveryOrders();
$_Order->order_no = $order_no;
$_Order->eta = $eta;
$_Order->save();
$POProduct = array();
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[] = new DeliveryOrderProducts();
$POProduct[] = $_getPOProduct->order_id;
$POProduct[] = $_getPOProduct->item_id;
$POProduct[] = $_getPOProduct->qty;
$POProduct->save();
}
But, this output an error.
Call to a member function save() on array
Please help me. Thanks.
If you wish to copy records from one table to another or just duplicate a record in the same table you could simply use the repliacate() method.
$user = User::findOrFail($id);
// replicate (duplicate) the data
$staff = $user->replicate();
// make into array for mass assign.
//make sure you activate $guarded in your Staff model
$staff = $staff->toArray();
Staff::firstOrCreate($staff);
Note: in case you're only duplicating on the same table replace Staff with User on this example.
You are trying to run the save method on the array but what you want is to use it on the array index instead.
Change your foreach to this and it should work (assuming columns are the same).
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = new DeliveryOrderProducts();
$POProduct[$i]->order_id = $_getPOProduct->order_id;
$POProduct[$i]->item_id = $_getPOProduct->item_id;
$POProduct[$i]->qty = $_getPOProduct->qty;
$POProduct[$i]->save();
}
You can shorten this by using forceCreate.
foreach($_getPOProducts as $i => $_getPOProduct)
{
$POProduct[$i] = (new DeliveryOrderProducts())->forceCreate($_getPOProduct->only(['order_id', 'item_id', 'qty']));
}
In Laravel 4.2, I have the following code:
$thingIds = [];
foreach ($this->things as $thing) {
$thingIds[] = $thing->id;
}
$thong->things()->sync($thingIds);
$thong->save();
Which seems to work for me, however in my pivot table I have an order column that isnt being updated/synced correctly. The order is set to 1 for each item in the pivot table, however I want the order to be representative of the order of the ids in $thingIds.
Is this possible?
Is it possible to update an additional column in the pivot table using ->sync()?
After the suggestion in the comments, I have also tried the following code:
$thingIds = [];
foreach ($this->things as $index => $thing) {
$thingIds[$thing->id] = ['order' => $index];
}
$thong->things()->sync($thingIds);
$thong->save();
And I have tried
$thingIds = [];
$order = [];
foreach ($this->things as $index => $thing) {
$thingIds[] = $thing->id;
$order[] = ['order' => $index];
}
$thong->things()->sync(array_combine($thingIds, $order));
$thong->save();
But neither of these is working (the order is still 1 for each item in the pivot table). Can anyone explain what I am doing wrong?
If I do the attaching one at a time, like so:
foreach ($this->things as $index => $thing) {
$thong->things()->attach($thing, ['order' => $index]);
}
The order comes out correctly in the pivot table. How can I get the same effect but whilst still using ->sync()?
Its an online result marker. Once the user clicks save it gets the CA(Continious assessment) and it gets the Exam marks and the teachers remark for the particular student. I want to know how i can insert these fields into my database the right way.
return $request->all();
the above code returns the image below
$i = 0;
foreach($request->id as $id) {
$model = new Model;
$model->user_id = $id;
$model->ca_mark = $request->ca_mark[$i];
$model->exam_mark = $request->ca_mark[$i];
$model->remarks = $request->remarks[$i];
$model->save();
$i++;
}
Query Builder
$i = 0;
foreach($request->id as $id) {
DB::table('table')->insert([
'user_id' => $id,
'ca_mark' => $request->ca_mark[$i],
'exam_mark' => $request->ca_mark[$i],
'remarks' => $request->remarks[$i]
]);
$i++;
}
The above code has been written based on an assumption of the database table structure. In short, foreach on the ID's as this would be the student ID, and take the ca_mark, exam_mark and remark based on the key of the id.