Hi is there a way to do something like:
$model->name = 'newname'
$model -> save()
Change database connection
$model save()
Change back.
I know you can do it with manual queries
DB::Conection(conectio1)->update($SQLString)
DB:Coneection(conection2)->update($SQLString)
MYSQL replication is not instant
thnx in advance
I have actually never tried that but it should be possible using the setConnection() method of your model.
$model->setConnection('connection2');
But you will have to replicate the model before you change anything on the original model instance because otherwise it won't recognise changes of the same attributes with the same values anymore (if they don't differ from the values you used before).
$model2 = $model
->replicate()
->setConnection('connection2');
$model->name = 'name';
$model->save();
// You need the replicated model here because if you used the same model
// with a different connection the model can not say that `name` has changed
// because the value hasn't changed.
$model2->name = 'name';
$model2->save();
I found the easiest way.
public function saveMultipleDatabases($db)
{
Config::set('database.default', $db);
$model->name = 'newname'
$model->save()
}
Related
Hey i want to save data to my database with cakephp 3.8. All works but i added a new field "created_by" and changed it in the models folder.
this is my RequestTable.php
public function validationDefault(Validator $validator){
.... (more, but not important)
$validator
->scalar('created_by')
->maxLength('created_by', 100)
->allowEmptyString('created_by');
return $validator;
}
My entity file "Request.php"
in the top
* #property string|null $created_by
and
protected $_accessible = [
... (more)
'created_by' => true,
];
My code where i want to save the data:
$request = $this->Requests->newEntity();
$session = $this->getRequest()->getSession();
if(!empty($session->read('Auth.User.username'))){
$this->request->data['Requests']['created_by'] = $session->read('Auth.User.username');
}
$request = $this->Requests->patchEntity($request, $this->request->getData('Requests'));
if ($result = $this->Requests->save($request)) {
...
}
At the empty check it goes in the clause. After the patchEntity the result is the correct data. The same in the save.
The column in the table looks like
created_by varchar(100) DEFAULT NULL
I dont know why it doesnt save the data. If someone have more questions about the code please ask :)
Without an error message. It would be hard to determine where is the flaw. One thing you might consider is checking the database if it is busy handling another process. If there are flood requests that makes your request locked.
I dont know why, but if I create a new database with the same schema it works. Thank you all for your help :)
There is an existing project only for one country. But for now, it should be used for multiple countries. So I need some place to change timezones. I decided to update & insert in only London/Sydney timezone. I need to change the timezone for all select queries. I just tried with middlewares, but I could not achieve it. Please give your suggestions.
Linux server, MySQL, Laravel, Vagrant
namespace App\Http\v2018_06_12\Middleware;
use App;
use App\Order;
use Closure;
class LocaleMiddleware
{
public function handle($request, Closure $next, $guard = null)
{
$locale = ($request->hasHeader('locale')) ? $request->header('locale') : 'uk';
$timezone = env('APP_TIMEZONE');
if ('aus' == $locale) {
$timezone = 'Australia/Sydney';
}
config(['app.timezone' => $timezone]);
date_default_timezone_set($timezone);
print_r(Order::select('delivery_time')->orderBy('id', 'DESC')->first()->toArray());
return $next($request);
}
}
in my db structure
service_request type enum('towel','tissue','napkin')
then have a model
* #property string $service_request
then in my view
<?= $form->field($model, 'service_request')->checkBoxList([ 'towel' => 'Towel', 'tissue' => 'Tissue', 'napkin' => 'Napkin']) ?>
then when i choose towel, tissue and napkin then submit the form, it's have an error said
Service Request must be String
please help me
Thank You
Like Joji Thomas said, checkBoxList prodices an array.
You need to change your database structure so that it supports 1-to-many relations (each $model can have multiple service_requests) if you want to save this. Unfortunately Yii is not very good at this sort of thing out of the box so you have to do a bunch of things yourself.
First you need to create a ServiceRequest ActiveRecord.
Then your $model needs to have a relation like:
public function getServiceRequests() {
return $this->hasMany(ServiceRequest::className(), ['model_id' => 'id'];
}
Then in your controller (model create action) you will need to do something like this:
foreach (Yii::$app->request->post('ServiceRequest',[]) as $data) {
$item = new ServiceRequest($data);
$model->link('serviceRequests', $item);
}
If you wanna update the checkboxes too then you need to do something similar in your model update action as well.
Please change checkBoxList to radioList, because when selecting multiple values service_request becomes an array. Enum type can handle only string values.
First change your filed datatype from enum to varchar. enum only takes a single string value.
Secondly you need to implode service_request array to string for save to db.
Use bellow code before the model save function :
$model->service_request = implode("," , $model->service_request);
$model->save();
Everytime i try attempt to update a row i receive an error which says "something is required". In codeigniter you can update rows without the need to set everything to null in the mysql tabel settings.
I just want to update one value not the entire row.
Is this possible?
if ($users->save() == false) {
echo "Umh, We can't update the user right now: \n";
foreach ($users->getMessages() as $message) {
echo $message, "<br>";
}
$this->flash->error("Error in updating information.");
$this->response->redirect('user/profile');
} else {
echo "Great, a new robot was saved successfully!";
$this->flash->success("Member has been updaed successfully.");
//$this->response->redirect('user/profile');
}
Your isseue happens because you have already filled table and not yet properly defined model. Phalcon is validating all fo model data BEFORE trying to save it. If you define your model with all defaults, skips etc. properly, updates will be fired on single columns as you wish.
If you have definitions, that does not allow nulls, but you need an empty or default value there anyway, you may want to use 'beforeCreate' actions in model implementations. Also if there are things with defaults to set on first insert, you may wanto to use skipAttributes method.
More information is in documentation: Working with Models. So far best bit over internet I've found.
Also, below is an example for nullable email column and NOT NULL DEFAULT '0' 'skipped' column from my working code:
public function initialize() {
$this->skipAttributesOnCreate(['skipped']);
}
public function validation()
{
if($this->email !== null) {
$this->validate(
new Email(
array(
'field' => 'email',
'required' => true,
)
)
);
if ($this->validationHasFailed() == true) {
return false;
}
}
}
You do want errors of "something is required". All you're missing are just proper implementations of defaults over models. Once you get used to those mechanics, you should find them easy to handle and with more pros than cons.
What you are doing is called an insert. To set a column to a different value in a pre-existing row is called an update.
The latter is flexible, the former in not.
I highly recommend not treating a database like this is what i feel like
Put all the data in. Null is your enemy
Is there a way I can use Zend_Db to make updates and insert crossing multiple (two) databases?
Example,
UPDATE database1.tableA AS a1, databse2.tableA as a2 SET a1.content = a2.content WHERE a1.id = a2.id
How could I do this with Zend_Db_Adapter_Pdo_Mysql?
I have multiple databases defined in my application.ini file
I have used something like this:
// REGISTRY
Zend_Registry::set('configuration', $configuration);
foreach($configuration->database as $type => $database){
$db[$type] = Zend_Db::factory(
$database
);
}
Zend_Registry::set('db', $db);
Upon creating your model you specify which db you want in the models constructor
$newModel = Model_NewModel($db['db_key_name']);
You then have 3 options, you can either manually code your own object to extend Zend_Db_Table_Abstract and have a multi-db-update function
/* the code for this example is pseudo code, so it probably wont work but the concept is still good */
class Model_NewModel extends MoakCustomDbClass{
function multi_db_update($db1, $db2, $update, $where)
{
$originalDb = $this->_db;
$this->_db = $db1;
$this->update($update, $where);
$this->_db = $db2;
$this->update($update, $where);
$this->_db = $originalDb;
}
}
, write your own custom query by calling
$newModel->query('UPDATE QUERY');
or running 2 models both pointing at different databases
$newModelA = Model_NewModel($db['db_key_name_A']);
$newModelB = Model_NewModel($db['db_key_name_B']);