Yii2- Not able to insert/delete rows using console controller - activerecord

I am trying to implement email queue in my project which uses CRON.
I am adding a row in one table and deleting a row from another table using CreateCommand of yii2. Database is mysql.
The entire code is executed and it does not display any error. But the rows are not added or deleted from the database.
I have also tried doing the same thing using ActiveRecords but it does not work. Hence I have used CreateCommand.
Below is the code which I am using -
$connection = \Yii::$app->db;
$result = $connection->createCommand()->insert('email_queue_completed', $arrInsert)->execute();
if(!empty($result))
{
$connection->createCommand()
->delete('email_queue', ['id' => $mail->id])
->execute();
}
$arrInsert is an array containing key value pairs of values to be inserted.

Related

How to get the list of inserted ids from the insert() method to use with the syncWithoutDetaching() method?

I have Files and Folders models that are related by a many-to-many relationship with a folder_file pivot table.
I want to insert files in bulk using the insert() method, then use the list of inserted ids with the syncWithoutDetaching() method to update the pivot table, | first create the $data_array in a foreach loop that does other things as well:
$data_array = [];
foreach (...) {
// ...
$data_array[] = $row;
}
then I want to insert the data and update the pivot table:
File::insert($data_array);
$folder->files()->syncWithoutDetaching($array_of_inserted_ids);
Is it possible to get the list of inserted ids from the insert() method?
Or maybe there is a more efficient way for better DB performance?
At first I just wanted to create the record and update the pivot table inside the foreach loop that creates the $data_array so that on every iteration it would create and update the tables, but that could be bad for performance with that many queries?
You could use the createMany() here. Instead of inserting the files then get the ids of inserted data. It will accept an array of data so that you could directly insert your array of files then connecting them to the folder.
$folder->files()->createMany($data_array);

Laravel 5.7.13 - FirstOrCreate/FirstOrNew not storing value

I'm trying to update a table with two columns 'id' and 'comp_id'. I only want 'comp_id' to exist in the table one time, so I'm using firstOrCreate to do this.
This call is creating a record in the table because the id auto-increment keeps going up every time I try this, but the comp_id value is not being saved.
$connections = $connectionTable->where('base_id', $baseId)->get();
$noMatchTable = new noMatch;
foreach($connections as $connection){
$rec = $noMatchTable->setTable($comparisonId.'_no_match')->firstOrCreate(['comp_id' => $connection->comp_id]);
}
I've also tried.
$rec = $noMatchTable->setTable($comparisonId.'_no_match')->firstOrNew(['comp_id' => $connection->comp_id])->save();
In both cases $rec->id shows a new id.
Fillable for the model is set correctly
#fillable: array:1 [
0 => "comp_id"
]
What frightfully simple thing am I missing?
I did some reading on this, and it seems like updateOrCreate() in Builder.php calls firstOrNew()in the same file. If you look at firstOrNew() it will return a new model instance, which means your setTable() will not work as the new instance will contain the default table name. I like the solution posted here
Update the table name at runtime not working - laravel Eloquent ORM
Sadly there is no way to dynamically set a table name and use updateOrCreate()

MySQL/php: I created database and tables, when I try an INSERT I have #1146

I'm writing an installation script in php, this script has to ask the user some data and then store them in a XML file and on a database.
Here is the procedure:
1) Insert data;
2) Save configuration data (such as database name,user,password,host,port) in a XML file
3) Using those data to install a database (I have an empty dump I use to create it)
4) Insert in the "admin" table the first user data (taken from the form in point 1)
Now, everything works fine until point 4.
When I try to access the database MySql always returns my an error #1146 saying that the table doesn't not exists.
This is my custom JSON log:
{
"Status":"KO",
"Reason":"SELECT * FROM bbscp_admin_user; || Table 'adb.bbscp_admin_user' doesn't exist",
"Errno":1146
}
Obviously I checked both with phpMyAdmin and mysql (from cli) and I can say that both DB and Table DO exists.
Here is the part where I create the DB: [this works fine]
$Install = Install::getInstance();
$sqlscript = str_replace("__DBNAME__",
$config_info['dbname'],
file_get_contents('../config/bbscp-base-db.sql')
);
$connection = mysqli_connect($config_info['dbhost'],
$config_info['dbuser'],
$config_info['dbpwd']
) or die("Unable to connect! Error: ".mysql_error());
if(mysqli_query($connection,'CREATE DATABASE '.$config_info['dbname'].';')){
echo 'Database successfully createad';
mysqli_close($connection);
}else{
die('ERROR CREATING DATABASE!');
}
Here the part where I populate the database from the dump (it only add the tables)
$connection = mysqli_connect($config_info['dbhost'],
$config_info['dbuser'],
$config_info['dbpwd'],
$config_info['dbname']
) or die("Unable to connect! Error: ".mysql_error());
if(mysqli_multi_query($connection, $sqlscript)){
echo 'Database successfully imported';
mysqli_close($connection);
}else{
die('ERROR IMPORTING DATABASE');
}
Now the decisive part, I open a connection with the database (using a library that I've developed in the past years and has always worked fine)
$DB = new Database(Install::getInstance());
$Q = new Query();
$DB->connect();
$query = $Q->addNewUser($config_info['nickname'],
$config_info['password'],
$config_info['firstname'],
$config_info['lastname'],
$config_info['email'],
0); // this just returns the query string I need
// the query in this case is:
// INSERT INTO bbscp_admin_user
// (nickname,password,firstname,lastname,mail,confirmed)
// VALUES (the ones above);"
$res=$DB->startQuery($query); // THIS IS WHERE THE ERROR IS RETURNED
// this function only wraps the mysqli_query and returns a custom JSON
I've tried a lot of solution.. The tables DO exists but every query I try to invoke at this point doesn't work because apparently "table doesn't exist" (even using mysqli function instead of mines).
Thanks in advance and sorry for the long question! :-)
EDIT 1
During this days I've changed a lot of code, I tried using different implementation using functions, objects, redirects but none of them seems to work.
The thing is always the same:
It creates the database
Returns the error code when trying to add the user
If I refresh the page it correctly adds the user

laravel4 update additional columns in pivot table

I'm trying to update additional column data in a pivot table in a many to many relationship.
I have two tables - reservation and resource linked with a pivot table. I can attach and am working with the model. However I'm struggling to update one of the additional columns in the pivot table.
I have an object: '$reservation' From that object I created another object $resources using:
$resources = $reservation->resource()->get();
I'm then iterating through $resources using a foreach loop as follows
foreach($resources as $resource ) {...}
I then want to update a column called gcal_id and am using the following:
$resource->pivot->gcal_id = "TEST";
$resource->save();
If I var_dump the model I can see the property exists to the correct value but in the database itself the entry is not being updated - so the save is not working
I have the columns listed in both sides of the relationship with this:
->withPivot('start', 'end', 'quantity', 'product_id','gcal_id')
Given I have the resource object how can I update a column correctly in the pivot table and save to database?
Thanks
After that you set the attribute on the pivot:
$resource->pivot->gcal_id = "TEST";
You seem to save the resource and not the pivot:
$resource->save();
If you want the pivot to be saved, saving the resource is not enough. Call save on the pivot instead:
$resource->pivot->gcal_id = "TEST";
$resource->pivot->save();
An alternative instead of save method, is the method Illuminate\Database\Eloquent\Relations\BelongsToMany\updateExistingPivot()
$reservation->resource()->updateExistingPivot($resource_id, ['gcal_id' => 'TEST']);
Or
$reservation->resource()->updateExistingPivot([1, 4, 5, 6], ['gcal_id' => 'TEST']);
This work for me in Laravel 4.2

Doctrine toarray does not convert relations

I followed doctrine documnetation to get started. Here is the documentation.
My code is
$User = Doctrine_Core::getTable("User")->find(1);
when I access relations by $User->Phonenumbers, it works. When I convert User object to array by using toArray() method, it does not convert relations to array. It simply display $User data.
Am I missing something?
By using the find method you've only retrieved the User data which is why the return of toArray is limited to that data. You need to specify the additional data to load, and the best place to do this is usually in the original query. From the example you linked to, add the select portion:
$q = Doctrine_Query::create()
->select('u.*, e.*, p.*') // Example only, select what you need, not *
->from('User u')
->leftJoin('u.Email e')
->leftJoin('u.Phonenumbers p')
->where('u.id = ?', 1);
Then when toArray'ing the results from that, you should see the associated email and phonenumber data as well.
I also noticed an anomaly with this where if you call the relationship first then call the ToArray, the relationship somehow gets included. what i mean is that, taking your own eg,
$User = Doctrine_Core::getTable("User")->find(1);
$num= $User->Phonenumbers->office; // assumed a field 'office' in your phone num table
$userArray = $user->toArray(true);
In the above case, $userArray somehow contains the whole relationship. if we remove the $num assignment it doesn't.
am guessing this is due to doctrine only fetching the one record first, and it's only when you try to access foreign key values that it fetches the other related tables

Resources