How to Update Data from Select Field Laravel - php

I have a number of select fields in which I'm saving the data to an associated table that stores two ids (no id column on the table, just two id's from each associated table). I have no problem with actually creating a record and after some tinkering updating an existing record. select example
What I'm having trouble with is using Laravel updateOrCreate method, it doesn't update the original record but creates a new one + the old one. Basically, creates a second record instead of updating the original.
I'm not entirely sure what to do here. If I've already set a select value in the database but want to update that particular one, as well as have the option to set the second select how would I go about doing it? Code example below of how I'm getting my current (incorrect) solution
$contractors = $request->get('contractors');
if($contractors) {
foreach ($contractors as $contractorId) {
if (isset($contractorId)) {
$interestedContractor->updateOrCreate([
'project_id' => $project->getId(),
'contractor_id' => $contractorId
]);
}
}
}
As this is my first question if anything is unclear please let me know and I will clarify.
Also the relationship is setup by a hasManyThrough if that helps at all.

Related

Laravel Save Method Isn't Updating Record

In one of my controllers, I am needing to update a specific record in another table. I have code to find the table, update the specific column, and save it. My problem is that the record is never updated. I have ensured that the column is fillable.
Here is the code that is giving me problems:
$portfolio = Portfolios::where('id', $request->portfolioID)->first();
$portfolio->totalValue = $portfolio->totalValue + $cd->currValue;
//dd($portfolio);
$portfolio->save();
At the die and dump that is commented out, I can compare the attributes shows the correct value and the original value was the previous value, which is still retained after the save.

Updating my table with save () with Eloquent/Laravel 5.3 is updating all rows instead of one

I am trying to update one row using eloquent Model/Laravel 5.3. Instead of updating one row, it is updating the column I want to update but in every row in the table.
I am sure I am just missing something but I can't just look at it anymore. Any help would be appreciated...
$userUpdate = userTable::placeid($placeId)->userid($userId)->regid($regId)-key($key)->first();
That gets me one row as a result.
then...
$userUpdate->VALUE = $value;
$userUpdate->save();
These three lines update the VALUE column in the table but every single row and not just the one I pulled.
You can also use update() as:
userTable::placeid($placeId)->userid($userId)->regid($regId)->key($key)->update(['VALUE' => $value]);
Also, make sure that your VALUE column is fillable is your userTable model.

Update post/row, instead of creating new one

I am building a system, where you can create blog posts for your website.
In there I have an ajax-function which is saving a draft of your post every two minutes.
In this way you're not losing your work if your computer or internet crashes.
But right now, it is saving a new row every time it auto-saves. How to I do, so instead of creating multiple rows, it is updating the row instead?
I have already tried with ON DUPLICATE KEY UPDATE, which didn't work. I think it might be because that it requires an unique field in the form. But the only unique in my database is the actual ID of the post/row.
This is the code I tried:
INSERT INTO blog (title, text, date)
VALUES ('$blog_title','$blog_text','".time()."')
ON DUPLICATE KEY UPDATE
title='$blog_title', text='$blog_text', modified_date='".time()."'
I have an idea, to get the post/row ID, when the post is auto-saved the first time. Here I could use mysql_insert_id(). Then this ID could be stored in a hidden input field and when it auto-saves again, it will see that there already is a post/row with that ID, and then it will just update instead of creating a new one.
Is that a good and safe solution, or should I do something else?
I can't seem to find a better one.
I have found some other similar questions, but they where using JSON, which I haven't worked with yet.
Hope someone can help me with this :)
When you create a new row, put the ID into a hidden field. Then the code to process the input can do:
if ($_POST['id']) {
// update existing row
} else {
// insert new row and put ID into hidden field
}
There's no need to use ON DUPLICATE KEY because you know from the input data whether it's indended as a new entry or an update.

Inserting an ID from one table into another when a new record is inserted

I have a form, which contains an employees personal information. I update the form, and it inserts into a table, called employee_info. It updates the table with the details and inserts a NEW ID(employee_id). In my database, I have another table called department_info, and the field which is relevant is department_id. This is the php markup, for inserting data into the database:
$sql_data_array = array('employee_firstname' => $employee_firstname); //other variables go here
if (ACCOUNT_DOB == 'true') $sql_data_array['driver_dob'] = tep_date_raw($driver_dob);
tep_db_perform(TABLE_EMPLOYEES, $sql_data_array);
$employee_id = tep_db_insert_id();
What I need to do is, when the form is updated, and data is inserted into the employee_info table, I need it to insert a new id for employee_id(which is already happening), and also to insert the department_id into the employee_info table.
The department_id is used to login, and I want to show a list of the employees, which belong to the department. Can anyone tell me how I would do this?
When you insert with PHP, most of the implementations return so called last insert id. This is a value of AUTO_INCREMENT column.
Even if your implementation does not support it, there should be a function that returns it.
EDIT:
From your update, this seems to be osCommerce. The problem with your code is that method tep_db_perform is used to insert one or MORE elements. What will happen, if you insert 2 rows? But in simple case, use tep_db_insert_id(), it should return last id.
php function mysqli_insert_id retrieves the ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT). Get this id and use it in other tables.

CakePHP: Insert record with specific id

This is essentially the same question as CakePHP: Is it possible to insert record with pre-defined primary key value?. In CakePHP 1.2 I want to insert a record with a pre-determined id. The id's value is determined by an external system, but unlike in the linked question I have no control over that system, so the solution to that question is not an option for me.
If the id field of a model is set when calling $model->save(), Cake will always try to update the record. Cake will even set the id to false, if a record with that id does not exist already [1]:
<?php
function save($data = null, $validate = true, $fieldList = array()) {
// snip
if (!$this->__exists && $count > 0) {
$this->id = false;
}
// snip
}
Saving the model first and then updating the id manually is also not an option, because this would break referencial integrity (this is an architectural limitation that I also have no control over).
So how can I force CakePHP to insert the record with a specific primary key?
Some background around the problems I'm facing:
The application I'm working on is backed by a Postgres database, so new primary keys are determined by sequences. There is a process where an external system will SELECT nextval('my_model_sequence'), do some work with that id and then pass it to the CakePHP application, where I want to INSERT a my_model record with that id.
There is no way for me to invoke the external process after saving the record. There is also no way for me to modify the external process at all.
[1] http://api12.cakephp.org/view_source/model/#l-1260
If you want to create a record with specific id just make sure you fill id field
$this->data['ModelName']['id'] = $your_id;
Also before calling:
$this->save($this->data);
you should remember to call
$this->create();
which will reset the model state which let you create new record.
Finally you should try:
$this->ModelName->create();
$this->ModelName->save($this->data);
On the other hand as I read your post and trying to imagine your tables structure I recommend you thinking over leaving the id field alone and trying to make this foreing id a Foreign key. Is that an option for you?

Categories