Laravel : How save array in database? - arrays

I need your help because I can't save array from form in the pivot table. If someone can show me how because this is going to drive me crazy.
So I have a exam form with input number in foreach and which has a dynamic name.
And I have two total results to.
This is my data form :
I want save my input number question in pivot table and the results on another table.
For the result it's ok but it's for save in pivot table I have a problem.
Thanks to help me.
In my controller I make this :
$data = $request->all();
foreach($data as $question_id => $answer_id){
$result = new PratiqueReponse();
$result->question_id = $question_id;
$result->answer_id = $answer_id;
$result->save();
}
But not working.

You did not share much information, so i can only guess but i think you should save to db like this:
$data = $request->all();
foreach($data['questions'] as $question_id => $answer_id){
$result = new PratiqueReponse();
$result->question_id = $question_id;
$result->answer_id = $answer_id;
$result->save();
}
you need to loop trough questions, not the whole array.

Related

Cakephp Update multiple records or create new one if id doesn't exist in database

hello I have an edit form which displays the input fields.I am displaying the data from database in those fields so user can edit them. And also there is a button which ask to add new field. I am able to edit multiple fields but the problem is how can I create a new field in database if there is no existing id of the record.
Note: For the new field I am sending 0 id so that I can check in cakephp that it has a new field.
foreach ($exp as $k => $v) {
$dat[$k]["prp_id"] = $prpid;
$dat[$k]["exp_company"] = $v['company'];
$dat[$k]["position"] = $v['position'];
$dat[$k]["exp_id"] = $v['exp_id'];
}
$this->Experience->saveAll($dat, array('conditions' => array('exp_id' => $v['exp_id'])));
This is updating all the fields. Btw I am also not sure why its working correctly as I am here $v['exp_id'] sending only one value because its out of the loop but it is working perfectly meaning I can be able to multiple fields which I am not sure how. So In the end I have two problems. One is to create a new record if exp_id is 0 and second is why my this code works good for updating records.
Try this:
foreach ($exp as $k => $v) {
$dat[$k]["prp_id"] = $prpid;
$dat[$k]["exp_company"] = $v['company'];
$dat[$k]["position"] = $v['position'];
if ($v['exp_id'] != 0) {
$dat[$k]["exp_id"] = $v['exp_id'];
}
}
$this->Experience->saveAll($dat);

How to use findAll() in yii2?

I want to know how can i get all data of user with array id for where condition
In yii you could do something like this
$students = Student::model()->findAll("id IN ({$_POST['studentIds']})");
or
$userDtls = Student::model ()->findAllByAttributes ( array (
'id' => explode ( ",", $_POST ['studentIds'] )
) );
Now in yii2 CDbCriteria is not there, so which approach should i use to achieve same thing??
I have tried this but it only returns data for first id in the array
$result = Users::findAll([ 'id'=> $_POST ['keylist']]);
In documentation it is written that we can use this
$result = Users::findAll([1,488,489]);
But my array $_POST['keylist'] is something like this
keylist{
0='1'
1='5'
2='8'
}
I have also tried this
$ids = \Yii::$app->request->post('keylist', []);
$result = Users::findAll($ids);
And still returns data for first id in the array here is the screenshot
Thats why it doesnt work i guess
thank you
$users = Users::findAll($ids); is a correct approach.
See what you can pass in $ids in official docs here.
As I explained you here, you should never trust data from $_POST and check it for existence and validate before using.
Example of getting and check for existence with Yii2:
$ids = \Yii::$app->request->post('ids');
Or just:
$ids = isset($_POST['ids']) ? $_POST['ids'] : null;
For more complex cases I'd recommend to create separate search model and use it with validation, see Gii's CRUD for example.
UPDATE: Pay attention to what you actually pass as $ids.
$students_ids = Yii::$app->request->post('studentIds');
if(isset($students_ids)) {
$result = Users::find()->where(['in','id',$students_ids])->all();
}
var_dump($result)
Try like this

Saving Array CakePhp

I wanna save values from an array into one field of my database. I've been using that code but nothing got saved.
$this->Form->input('Model.0.field1');
$this->Form->input('Model.0.field2');
$this->Form->input('Model.1.field1');
$this->Form->input('Model.1.field2');
Thanks.
I think you need to save data with json_encode() value.
// In your controller
public function test() {
if($this->request->is('post')) {
//If you want to insert in single row then you can use json_encode() and add to your colum.
$insert_data = json_encode($this->request->data);
$data = array();
// Load your model where you want save data
$this->loadModel('Test');
// set attribute name where you want to save
$data['Test']['value'] = $insert_data;
$this->Test->save($data);
//For viewing your data
$fetchedData = $this->Test->find('all');
foreach($fetchedData as $items) {
var_dump(json_decode($items['Test']['value']));
}
}
}
You can use implode() to generate comma separated data. If you want to use implode(), look at Inserting an array into a mysql database column

Laravel 4 foreach loop - wanting to display the last element

I am currently trying to set up an edit page where an order form is populated using json_decode to decode json information that was saved when the form was created. Because the form's size can change I have to create the correct number of inputs so that all the json data will have a place to be displayed. Fortunately as the inputs are numbered this should not be hard to do. Unfortunately I am not sure how to pick the last element of the json information that has been decoded. Currently I am using:
public function getEdit($id){
$order = Order::where('id', '=', $id);
if($order->count()) {
$order = $order->first();
$order->order_serialized = json_decode($order->order_serialized);
foreach($order->order_serialized as $key => $value){
$order->$key = $value;
}
return View::make('orders.edit')
->with('order', $order);
} else {
return App::abort(404);
}
}
to decode the information and it is working splendidly but I need to be able to pick up the last element to be able to find the total number of inputs and am not sure how I could do this without disturbing the foreach loop. Any and all help would be greatly appreciated!! Thank you so much!
You can use the count and toArray methods to find the last item.
$nItem = $order->count();
$aOrder = $order->toArray();
$aLastItem = $aOrder[$nItem-1];
Collections have a last() function to compliment the first() function.

Add a new translatable field to an existing translatable table in CakePHP 2.2

I'm using CakePHP's translatable behavior. I have a few existing fields working fine, but I'm having trouble adding a new translatable field to my model.
CakePHP uses an INNER JOIN to fetch all translatable fields from the database.
Now, if I add an extra translatable field to my model, all the translation records for that field won't exist in the database. And because of the inner join, whenever it tries to fetch ANY existing records from the database, it will return blank - because the INNER JOIN on the new field fails, and so the entire query returns nothing.
Surely people must have come accross this situation before. Is there an easy solution?
One solution would be to edit/override the core and make all the INNER JOIN's into LEFT OUTER JOIN's. Is there anything wrong with that?
Another solution would be to run an update on the translations table to create all the extra records for the new field, every time you add a new translatable field - but I hate that solution.
Is there a better solution? How have others dealt with this problem?
Thanks in advance.
OK, here's a way of making sure the records exist after each time you add a new translatable field. If you've got a better answer, add it, and I'll mark yours as correct.
PS - this is tested for my purposes. I'm using multiple translation tables (http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html#multiple-translation-tables). I think it should work for most situations, but if not, it should at least be a good starting point.
In your model (the model that actsAs Translatable), add the following method. What it does is takes an array of locales, and then for every record in the table, and for every translatable field, and for every locale (ie, 3 loops), it checks that a translation record exists. If a translation doesn't exist, it adds a blank one, so at least the INNER JOIN won't fail.
It returns an array of all the records it added, so you can then go through and check them or change their content or whatever.
Here's the model method:
function ensureTranslationIntegrity($localesToCheck){
$allRows = $this->find('all', array('fields' => array('id')));
$fieldsToCheck = array();
$translatableFields = $this->actsAs['Translate'];
foreach($translatableFields as $key => $value){
// actsAs Translatabe can take field names only, or Key => Value pairs - see http://book.cakephp.org/2.0/en/core-libraries/behaviors/translate.html#retrieve-all-translation-records-for-a-field
if(is_numeric($key)){
$field = $value;
} else {
$field = $key;
}
array_push($fieldsToCheck, $field);
}
$translateModel = $this->translateModel();
$addedRows = array(); // This will contain all the rows we have to add
foreach ($allRows as $row){
foreach($fieldsToCheck as $field){
foreach($localesToCheck as $locale){
$conditions = array(
'model' => $this->name,
'foreign_key' => $row[$this->name]['id'],
'field' => $field,
'locale' => $locale
);
$translation = $translateModel->find('first',array('conditions' => $conditions));
if(!$translation){
$data = $conditions; // The data we want to insert will mostly just match the conditions of the failed find
$data['content'] = ''; // add it as empty
$translateModel->create();
$translateModel->save($data);
array_push($addedRows, $data);
}
} // END foreach($localesToCheck as $locale){
} // END foreach($fieldsToCheck as $field){
} // END foreach ($allRows as $row){
return $addedRows;
}
And in your controller, you'd call it something like this:
public function ensure_translation_integrity(){
$locales = array('en_au','en_gb','en_nz','pt_br','xh_za');
$addedRows = $this->YourModel->ensureTranslationIntegrity($locales);
debug($addedRows);
}
Hope that helps someone, but like I said, I'd love to see a better solution if someone has one.

Resources