Laravel update Issue - php

Here is my code -
$updatecompany = DB::table('Companies')
->where('ID', (int)$companyid)
->update(array(
'CompanyName' => $companyname,
'CompanyAddress' => $companyaddress,
'CompanyEmail' => $companyemail,
'ContactName' => $contactname,
'CompanyCity' => $companycity,
'CompanyState' => $companystate,
'CompanyZip' => $companyzipcode,
'CompanyPhone' => $companyphone,
));
$updatecompany is always 0. What might be the problem?

One of most possible reasons is that you are updating with the same data in the database.
There needs one out of the box solution, of course if you can do it.
So, no rows are updating, even if the SQL is correct.
Here is my suggestion:
Add a new column updatedOn in DB Table Companies.
The type should be TIMESTAMP and add attribute ON UPDATE CURRENT_TIMESTAMP.
This way you will always get row affected and hence you get return value other than 0.

You don't need to cast $companyId to an integer there. It does not help Laravel's query builder.
Use dd($companyId) and dump the variable before you run the query and find out what it is.

Related

Laravel Eloquent - bulk update with whereIn array

I'm working on a project where I need to update many rows at once per coin Id.
in order to update all coins values, Im getting them all from the API, so for example I have back:
$coinsList= [[id="bitcoin", symbol="btc", name="Bintcoin"],[id="etherium", symbol="eth", name="Etherium"]];
and the database table columns is the following:
**| id | coin_id | symbol | name |**
now, I want to update all values to the database, according to the id only, so this is what I did:
// first get ids from my table
$exist_ids = Coinlist::all('coin_id')->pluck('coin_id')->toArray();
//get all ids to update (to ignore other ids):
$updatable_ids = array_values(array_intersect($exist_ids, $allCoinIds));//result for example is: array("bitcoin","etherium");
//and now, update the database:
Coinlist::whereIn('coin_id', $updatable_ids)
->update([
'symbol' => $coinsList[$key]['symbol'],
'name' => $coinsList[$key]['name'],
'updated_at' => now()
]);
the problem is, I don't have the "$key" in order to update the right row, what am I missing here?
Thanks!
Here is a good way to solve it:
in the beginning, I used this library: https://github.com/mavinoo/laravelBatch
to update many dynamic rows, but it was really slow, then thanks to Yasin, I moved to: https://github.com/iksaku/laravel-mass-update and now it works way better.
the implementation is simple, add a simple code to the Model class, then add:
User::massUpdate(
values: [
['username' => 'iksaku', 'name' => 'Jorge González'],
['username' => 'gm_mtz', 'name' => 'Gladys Martínez'],
],
uniqueBy: 'username'
);
while uniqueBy is the key for the row, and add other columns values to change them dynamically.

Column in SQL being deleted on UPDATE

I have a table of values that uses a Where clause to find the row and then updates the values in the row. However it is deleting the value it is searching for after it is already found. So it finds the row using the stockid (not a PK) and updates the row, but leaves the stockid blank afterwards
$data = array(
'towSet' => $towSet,
'transWare' => $transWare,
'oceanFreightBooked' => $oceanFreightBooked,
'BOLrec' => $BOLrec,
'BOLsent' => $BOLsent,
);
$this->db
->where('stockid', $stockHold)
->update('logistics_tracking', $data);
The Strange part is that using this code doing the same thing it works perfectly fine
$data = array(
'recTitle' => $recTitle,
'recPOA' => $recPOA,
'recTitleState' => $recTitleState,
'titleSent' => $titleSent,
);
$this->db
->where('stockid', $stockHold)
->update('title_tracking', $data);
So as a reminder all the other values (towSet, transWare, oceanFreightBooked, ect.. ) all insert and it just blanks out the stockid after updating
Any ideas would be greatly appreciated
Yeah the code was fine, apparently I was just doing too much with one function. Created an external function and passed through an array of the data. Weird.
Thanks for looking!

Laravel - update row with variable using fluent query builder

iam building my web app, and i need to the simplest thing, just update fields inside table with some variables,but its not working he doesnt do anything ,values of the fields remain just as it was.
public function post_eupdate(){
$update = DB::table('app_events')
->where('ev_id', '=', Input::get("id"))
->update(
array(
'ev_op1' => Input::get('op1'),
'ev_op2' => Input::get('op2'),
'ev_coef1' => Input::get('coef1'),
'ev_coef2' => Input::get('coef2'),
'ev_host' => Input::get('host'),
'ev_stime' => Input::get('stime'),
'ev_ns1' => Input::get('ns1'),
'ev_cat' => Input::get('cat'),
'ev_tip' => Input::get('tip'),
'ev_ns2' => Input::get('ns2')
)
);
Your update statements seams good.
My guess would be that the problem is that Input::get("id") isn't a valid id for app_events.ev_id
Try debugging this by replacing ->update with ->get(). If this return null you would know that my assumption is correct. (If not post it in you question.)
As this is the case you have to modify the Input and not this piece of code which makes your question no longer fitting for the problem.

How to insert value of subquery using Active Record?

i use Active record for inserting values to DB.
All other type of queries i do with custom query as it's much easier but the active record insert is quite nice.
So i have this code :
$comment = array (
'point_id' => $object->id,
'title' => $object->title,
'comment' => $object->comment,
'author_name' => $object->author_name,
'is_temp' => 0,
'parent_id' => $object->parent_id
);
return $this->db->insert('comments', $comment);
Now i want to be able to set is_temp as a subquery result, which is :
(SELECT allow_user_comments from subjects where id='somevalue')
How would one achive that?
I was hoping to avoid using third party libraries.
Well, i doubt the fact that that's how you're supposed to do it, but ain't CI all about that?
This is how i got it to work (removing is_temp from the $comment array ofcourse):
$this->db->set($comment);
$this->db->set('is_temp',
'(SELECT allow_user_comments from subjects where id='.$subject_id.')',FALSE);
$this->db->insert('comments');
Feel free to use https://github.com/NTICompass/CodeIgniter-Subqueries. I have used it and it works! Hope it would be useful. :-)

find by column name cakePHP

Hello I have been trying to understand how to get data from model by the name of field. I am using cakePHP, and I need to retreive a column's data from a table. The syntax is
> "select name from permissions"
So I tried to find out on book.cakephp.org, so I got the field function, but that only gives me the first value, while I have more than one values for this.
I tried do a
$this->Model->find(array('fields'=>'Model.fieldName'));
but I understood that the syntax itself is flawed.
Can somebody let me know what is the method to query based on column name.
$this->Model->find(array('fields'=>'Model.fieldName'))
You forgot the array function. Also:
$this->Model->find(array('fields'=>array('Model.fieldName')))
will work.
findAllBy will find all records based on the field name.
$this->Model->findAllBy<fieldName>(string $value, array $fields, array $order, int $limit, int $page, int $recursive);
For eaxample:
$this->Permission->findAllByName('Some Name');
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#findallby
Found it... hope it will help someone.
$workshop_lists = ClassRegistry::init('Workshop')->find('all',array(
'fields'=>array('user_id', 'title')
),
array(
'conditions' => array('user_id' => $this->Auth->user('id')),
'group' => 'Workshop.user_id',
'order' => 'posted DESC',
));
There is no way you can query out based on column name using one of the cake methods. You have to use the query method.
Syntax: $this->Model->('Select columnname from table');
$this->Model->find('all',array('fields'=>array('Model.fieldName')))
it works for me everytime.
If I understood well and you want not only 1 value but the whole values in the column 'name' from the table 'permissions'. In that case you could use:
$this->Model->find('list',$params);
(see explanation for 'find' here)
for the '$params' part you would use:
$params=array('fields'=>array('name'));
or putting all in a single line:
$arrayOfNames= $this->Model->find('list',array('fields'=>array('name')));
This will give you an array '$arrayOfNames' wich key is the 'id' (primary key) in 'permissions' table and wich value is the corresponding name in the field 'name' from the same table. This is the array would be something like:
'id'=>'name'
[23]=>'name1'
[28]=>'name2'
[29]=>'name3'
............
very much like I think you want. Hope it helps.
$this->Model->find('list', ['valueField' => 'fieldName']);

Categories