How to add array values to another array - laravel

I have two sets of array A and B, array A and B on submission is supposed to enter a database table.
A(result)
array:2 [
0 => 7
1 => 8
]
B
array:3 [
"student_test_id" => 8
"question_id" => 4
"test_id" => 3
]
EXPECTED RESULT
On submit, i want the values of Array A and B to enter this table like this
id| student_test_id | test_id | question_id |result
1 | 8 | 3 | 4 | 7
2 | 8 | 3 | 4 | 8
WHAT I HAVE TRIED
$result = $request->result;
$array_conv = array(
"student_test_id"=>$request->student_test_id,
"question_id"=>$request->question_id,
"test_id"=>$request->test_id,
);
foreach($request->result as $result){
$test_log = new StudentTestLog();
$test_log->student_test_id = $array_conv["student_test_id"];
$test_log->question_id = $array_conv["question_id"];
$test_log->test_id = $array_conv["test_id"];
$test_log->result = $result['id'];
$test_log->save();
if($test_log->save()){
return response()->json('Submited', 200);
}else{
return response()->json('Error Submitting', 400);
}
}
Please assist Thank you

When returning response from foreach except first all other iterations of loop are omitted as return ends method execution. You should move return statements outside the loop. Try something like this:
$array_conv = array(
"student_test_id"=>$request->student_test_id,
"question_id"=>$request->question_id,
"test_id"=>$request->test_id,
);
$data_to_persist = [];
foreach($request->result as $result){
array_push( $data_to_persist, [
'student_test_id' => $array_conv["student_test_id"],
'question_id' => $array_conv["question_id"],
'test_id' => $array_conv["test_id"],
'result' => $result['id']
]);
}
$saved = StudentTestLog::insert( $data_to_persist );
if($saved){
return response()->json('Submited', 200);
}else{
return response()->json('Error Submitting', 400);
}

Related

Storing array of ids as different entity in Laravel -Mysql

I have A Table
id Primary bigint(20)UNSIGNED AUTO_INCREMENT,
school_id bigint(20)UNSIGNED Foreign Key,
teacher_id bigint(20)UNSIGNED Foreign Key,
course_id bigint(20)UNSIGNED Foreign Key,
klass_id bigint(20)UNSIGNED Foreign Key,
I Want to add Some data To this table, My data is given below.
{
"school_id":5,
"teacher_id":2,
"course_id":[1,2,3],
"klass_id":[7,8,3],
}
How Can I store this data Like Below
--id|school_id|teacher_id|course_id|klass_id
----------------------------------------------
1 | 5 | 2 | 1 | 7
2 | 5 | 2 | 2 | 8
3 | 5 | 2 | 3 | 3
If the input is always gonna be in the format of
"school_id" will have 1 value,
"teacher_id" will have 1 value,
"course_id" will have x values,
"klass_id" will have x values,
Then you can do something like:
$mapped = [];
for($i=0; $i<count($data['course_id']); $i++) {
$mapped[] = [
"school_id" => $data['school_id'],
"teacher_id" => $data['teacher_id'],
"course_id" => $data['course_id'][$i],
"klass_id" => $data['klass_id'][$i]
]
}
Then you can call any eloquent or DB function to insert like:
Model::insertMany($mapped);
P.S: There must be a better way of doing it that I don't know of. :(
Are you trying to save this data manually? if yes, create database SEED and add these data in array format like below: create a class with command php artisan make:seeder CreateSeedTableName and add this below code
$arr = [
[
"school_id" => 5,
"teacher_id" => 2,
"course_id" => 1,
"klass_id" => 7
],
[
"school_id" => 5,
"teacher_id" => 2,
"course_id" => 2,
"klass_id" => 8
],
[
"school_id" => 5,
"teacher_id" => 2,
"course_id" => 3,
"klass_id" => 3
]
];
TableName::insert($arr);
or you can use loop if you have same format data in request.
$count = count($data['course_id']); //get course count
$schoolId = $data['school_id']; //get school id
$teacherId = $data['teacher_id']; //get teacher id
for ($i = 0; $i < $count; $i++) {
TableName::create([
'school_id' => $schoolId,
"teacher_id" => $teacherId,
"course_id" => $data['course_id'][$i],
"klass_id" => $data['klass_id'][$i],
]);
}

How to loop number and saved into table laravel

I have input and this input is will generate number sequentially like this
5.01
5.02
5.03
......
5.10
5.11
i get number 5 on first number is from my another data . u can see at my code .so how i can do this if this number start from '01' not '1' and if more than 10 this '0' in first number is deleted.
in my controller i saved in $data and looping this number from 01
So in my input controller is like that :
public function store(Request $request)
{
$data = $request['kode_induk'] + // i dont know what to do here for loop this input ,
$induk = IndukBelanja::create([
'user_id' => Auth::user()->id,
'kode_induk' => $request['kode_induk'],
'kode_rekening' => $data,
'uraian' => $request['uraian'],
'anggaran' => $request['anggaran'],
]);
if ($induk) {
return ['redirect' => route('rekening_induk')];
} else {
return response()->json([
'success' => false,
'message' => ' Gagal update!',
], 500);
}
}
how i can loop this number ? can someone help ?
Update its my database what i need
+----+------------+------------+------------+
| id |kode_induk |kode_rekening| uraian
+----+------------+------------+------------+
| 1 | 5 | 5.01 | some data
+----+------------+------------+------------+
| 2 | 5 | 5.02 | some data
+----+------------+------------+------------+
| 3 | 5 | 5.03 | some data
+----+------------+------------+------------+
| 4 | 5 | 5.04 | some data
+----+------------+------------+------------+
You can cast $data to int and then increment by 0.01 in a for loop.
$data = (int) $request['kode_induk'];
$numberOfSequencesToGenerate = 10;
for($i = 0; $i < $numberOfSequencesToGenerate; $++){
$induk = IndukBelanja::create([
'user_id' => Auth::user()->id,
'kode_induk' => $request['kode_induk'],
'kode_rekening' => $data + 0.01,
'uraian' => $request['uraian'],
'anggaran' => $request['anggaran'],
]);
}
The loop basically reads, run the the block of code while $i is less than $numberOfSequencesToGenerate. On each iteration increment $i by one.
I am assuming the DB field kode_rekening is of type double but if is not you can format it in PHP so is always has two decimal places with number_format(). Ex: number_format($data + 0.01, 2)

Laravel mass update with different value based on condition

I have a table structure like:
id //primary_key
value
changed_value //on update value column should not be updated instead changed value should be updated
status // 0 - default, 1- updated
am_id //foreign_key
Now, to mass update I am doing as follows:
Model::where('am_id',$request->am_id)
->where('value',$request->value)
->update([
'changed_value' => '$request->value',
'status' => 1
]);
However, we should not set status as 1 blindly, as there is one condition. It's if the value of value column is equal to the $request->value the status should be 0 instead.
How this scenario could appear?
Initially, after inserting the first row looks like
+-----+-------+---------------+--------+-------+
| id | value | changed_value | status | am_id |
+-----+-------+---------------+--------+-------+
| 1 | 20 | null | 0 | 1 |
+-----+-------+---------------+--------+-------+
After 1st update
+-----+-------+---------------+--------+-------+
| id | value | changed_value | status | am_id |
+-----+-------+---------------+--------+-------+
| 1 | 20 | 40 | 1 | 1 | // changed_value - 40 , status 1
+-----+-------+---------------+--------+-------+
After 2nd Update (let's say the value is updated to 20), in this case as the value === changed_value the status should be updated as 0 not 1
+-----+-------+---------------+--------+-------+
| id | value | changed_value | status | am_id |
+-----+-------+---------------+--------+-------+
| 1 | 20 | 20 | 0 | 1 | // changed_value - 20 , status 0
+-----+-------+---------------+--------+-------+
This means, during the model update in below-mentioned code. I want to insert a condition, if( value == $request->value) status = 0 else status = 1
Model::where('am_id',$request->am_id)
->where('value',$request->value)
->update([
'changed_value' => '$request->value',
'status' => 1
]);
Alternatively you could always use raw sql if performance was an issue.
DB::unprepared('
update model
set status = case when (changed_value = "'.$request->value.'") then 0 else 1 end
and changed_value = "'.$request->value.'"
where value = "'.$request->value.'";
')
Edit: You can do it in Eloquent with 2 queries with a subquery to filter the ids of the already updated rows.
// get ids of all matching status 1 but don't execute the query
$matches = Model::select('id')->where('am_id',$request->am_id)->where('value',$request->value)
->where('changed_value', $request->value);
// change matching status 1
Model::whereIn('id', $matches)
->update([
'changed_value' => '$request->value',
'status' => 1
]);
// matching not in status 1
Model::where('am_id',$request->am_id)
->where('value',$request->value)
->where('changed_value', '!=', $request->value)
->whereNotIn('id', $matches)
->update([
'changed_value' => '$request->value',
'status' => 0
]);
Try this one.
$value = Model::where('am_id',$request->am_id)->first()->value;
if($request->value == $value){
$status = 1;
}else{
$status = 0;
}
Model::where('am_id',$request->am_id)
->update([
'changed_value' => '$request->value',
'status' => $status
]);
Unfortunately, Eloquent was not designed to handle this kind of mass update (where you want different conditions) with a single query. You would have to step through the models, or resort to the query builder.
$models = Model::where('am_id',$request->am_id)->get();
$models->map(function ($model) use ($request) {
// status
$status = $model->value === $request->value ? 0 : 1;
// update model
$model->update([
'changed_value' => $request->value,
'status' => $status
]);
return $model;
});
EDIT: There are some query builder ideas on this page that might allow you to make something reusable, instead of just writing raw SQL any time you need to do this.
https://github.com/laravel/ideas/issues/575#issuecomment-300731748

How to merge multiple arrays in PHP and output the values together?

I have a situation while developing an application on Laravel. I have three arrays in the following order. I need to merge them and display their values in the following order too. Here , it goes.
stone_name['ruby','diamond','catseye'];
stone_weight[112,223,445];
stone_rate[1000,2500,670];
I need to merge these three arrays and display the out put in this order.
stone_info = array(stone_name[0] , stone_weight[0] , stone_rate[0]);
So that the final result will be like :
stone_info = array("ruby",112,1000);
I was in the same situation and I had done it in this way. May be this can help you out.
<?php
$stone_name = ['ruby','diamond','catseye'];
$stone_weight = [112,223,445];
$stone_rate = [1000,2500,670];
$result = mergeArrays($stone_name, $stone_weight, $stone_rate);
function mergeArrays($stone_name, $stone_weight, $stone_rate) {
$result = array();
foreach ($stone_name as $key => $name ) {
$result[] = array( 'stone_name' => $name, 'stone_weight' => $stone_weight[$key], 'stone_rate' => $stone_rate[ $key ] );
}
return $result;
}
print_r($result);
Output:
Array
(
[0] => Array
(
[stone_name] => ruby
[stone_weight] => 112
[stone_rate] => 1000
)
[1] => Array
(
[stone_name] => diamond
[stone_weight] => 223
[stone_rate] => 2500
)
[2] => Array
(
[stone_name] => catseye
[stone_weight] => 445
[stone_rate] => 670
)
)
DEMO

how to sum column value using group by collection in magento(USING MAGENTO STANDARD)

my table is like this and my collection is
$testmodel=Mage::getModel(test/p1)->getCollection();
my database table is below.
id cat_id rate p_id
1 1 4 1
2 1 2 1
3 1 3 2
4 2 5 3
5 2 3 1
and i want output like this in magento using collection
cat_id rate count_category
1 9 3
2 8 2
i found my PROBLEM correct code is below
$testmodel = Mage::getModel('test/p1')
->getCollection()
->addFieldToSelect('rate')
->addFieldToSelect('cat_id');
$testmodel ->getSelect()
->columns('SUM(rate) as total,COUNT(*) AS countCategory')
->group('cat_id');
if you use mysql4 as this model resource class then go to
Model/Mysql4/P1/Collection.php
here you need to add function
public function addGroupByCatId(){
$subSelect = clone $this->getSelect();
$CountsubSelect = clone $this->getSelect();
$subSelect->reset()
->from(array('rev' => 'youtable', 'SUM( rev.rate)')
->where('main_table.cat_id = rev.cat_id');
$CountsubSelect->reset()
->from(array('countrev' => 'youtable'),'COUNT(countrev.cat_id)')
->where('main_table.cat_id = countrev.cat_id');
$this->getSelect()
->join(
array('r' => 'youtable'),
'main_table.id = r.id',
array(
'review_sum' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
'count_category' => new Zend_Db_Expr(sprintf('(%s)', $CountsubSelect)),
))
->group('main_table.cat_id');
return $this;
}
OR: Resouce as resource model then goto
if you use mysql4 as this model resource class then go to
Model/Resource/P1/Collection.php
here you need to add function
public function addGroupByCatId(){
$subSelect = clone $this->getSelect();
$CountsubSelect = clone $this->getSelect();
$subSelect->reset()
->from(array('rev' => 'youtable', 'SUM( rev.rate)')
->where('main_table.cat_id = rev.cat_id');
$CountsubSelect->reset()
->from(array('countrev' => 'youtable'),'COUNT(countrev.cat_id)')
->where('main_table.cat_id = countrev.cat_id');
$this->getSelect()
->join(
array('r' => 'youtable'),
'main_table.id = r.id',
array(
'review_sum' => new Zend_Db_Expr(sprintf('(%s)', $subSelect)),
'count_category' => new Zend_Db_Expr(sprintf('(%s)', $CountsubSelect)),
))
->group('main_table.cat_id');
return $this;
}
and final you get
$testmodel=Mage::getModel(test/p1)->getCollection();
$testmodel->addGroupByCatId();

Resources