I want to delete updated value from db. Like if the notice is inserted of notice column in class table and I want to delete it. So what will be the query in yii2? Please help -
$model = Class::find()->where('id', $id)->one;
$model->delete();
Above query is for -
DELETE FROM class WHERE id = $id;
I want to write query like that in yii2 -
DELETE notice FROM class WHERE id = $id;
If you are searching using the primary key, you can use
$model = Class::findOne($id);
Then, for deleting (setting to null) the notice field, you just need to use
$model->notice = NULL;
$model->save();
Note that if the notice attribute is required, or not null, the save will fail.
Yii allows you to execute SQL command direct
https://www.yiiframework.com/doc/api/2.0/yii-db-command
$query = "DELETE notice FROM class WHERE id = {$id}";
Yii::$app->db->createCommand($query)->execute();
Related
I have an Eloquent model that has a column that is a number composed of various codes and at the end a number that should increment automatically. This last number is the same number I use to define the primary key of my model, so my question is:
Is there a way to use the AUTO_INCREMENT variable from my MySQL database?
If not, what is the best way to create a variable in Laravel that automatically increments?
example:
$code1 = $this->getCode1();
$code2 = $this->getCode2();
$autoIncr = ...;
$final_code = $code1 . $code2 . $autoIncr;
you can create a function that returns the next id (autoincrement) of your table and the insert the entry in your table;
$code1 = $this->getCode1();
$code2 = $this->getCode2();
$autoIncr = $this->getNextAutoincrement();
$final_code = $code1 . $code2 . $autoIncr;
//Insert in your table
$row = YourModel::create([
'finalCode' => $final_code
]);
private function getNextAutoincrement() {
//don't forget import DB facade at the beginning of your class
$id = DB::select("SHOW TABLE STATUS LIKE 'YOUR_TABLE_NAME'");
$next_id=$id[0]->Auto_increment;
return $next_id;
}
Hope I've helped you
I am trying to update the column with some other data but database table is not letting me update the table because of the NOT NULL constraints in it. I have this option of setting all the fields to NULL but I dont think that will be a good practice. Please I need a solution to it if anyone can help. I get the following error
Illuminate \ Database \ QueryException (HY000)
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (SQL: insert into users (subject_id, updated_at, created_at) values (?, 2019-07-30 13:46:42, 2019-07-30 13:46:42))
Previous exceptions
SQLSTATE[HY000]: General error: 1364 Field 'first_name' doesn't have a default value (HY000)`
I have tried setting all the values to NULL and it worked but I want to work with some fields setting as NOT NULL and update the ones which are NULL and also if we can fetch or set the fields automatically to what we have ?
This is my controller where I am trying to update the field if this is required or help you understand my problem
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$findSubject = Auth::user()->where('subject_id', $id);
$users = new User();
$users->subject_id = null;
$users->save();
// echo($findSubject);
// die();
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
The following should work for your code. As it was said in the previous comment, it's because you try to create a new instance of a user without inserting value.
It look like you are trying to delete the subject associate with the authenticated user, so I suppose that you don't really need to create a new user, instead I think you should dissociate the user and the subject. So, the following should work for your code.
The purpose of that variant is to take the authenticated user and put a null value for the subject_id.
public function deleteSubject($id) {
echo $id;
// die();
if(Auth::check()) {
$user = User::where('subject_id', $id)->first(); // This will get the user that have the subect_id, but it's assuming that only one user have this subject_id.
// You can also do this just uncomment the first line below and comment the other one above.
// $user = User::find(Auth::user->id);
$user->subject_id = null;
$user->save()
Session::flash("message", "You subject has been deleted. You can add a new Subject now.");
return redirect('/subjects');
} else {
Session::flash("message", "Please sign in to access this page");
return redirect('/signup');
}
}
I think that you should take a look about how MVC work.
https://selftaughtcoders.com/from-idea-to-launch/lesson-17/laravel-5-mvc-application-in-10-minutes/
You should also take a look at relationship in Laravel: https://laravel.com/docs/5.8/eloquent-relationships
MVC and Eloquent-Relationships will help you understand some function in laravel to achieve this kind of goal really quickly.
If you get a User model and a Subject model, you can simply do something like this:
$user = User->find(Auth::user()->id);
$user->subjects()->dissociate($id);
I'm not sure, but I think the Auth facade let you use the user model function, so maybe this could work to:
Auth::user()->subjects()->dissociate($id);
You should also take a look at middleware: https://laravel.com/docs/5.8/middleware
With middleware, you can put rules like the one you are using to send a message to the user saying that he/she need to be log in to access the page into the middleware and reusing it whenever you need.
I want to create new product in Sylius. I just tested:
$user = $this->getUser();
$repository = $this->container->get('sylius.repository.product');
$manager = $this->container->get('sylius.manager.product'); // Alias for appropriate doctrine manager service.
$product = $repository->createNew();
$product
->setName('Test product')
->setDescription('Des Product 2')
->setPrice(90)
->setUser($user)
;
$manager->persist($product);
$manager->flush(); // Save changes in database.
But it trigger an exception of slug. When I try $product->getSlug(), that returns empty. I don't know how does slug created in Sylius and where is the code for that?
It's a gedmo:slug, check ProductBundle\Resources\config\doctrine\model\ProductTranslation.orm.xml
Make sure you have a default locale configured and add this to your code:
$product->setCurrentLocale($locale);
$product->setFallbackLocale($locale);
Products are translatable, and I think this is what you're missing.
Check how a product is created in Sylius\Bundle\FixturesBundle\DataFixtures\ORM\LoadProductsData line 404.
I am coming from a previous enviornment where doing things like modifying queries and adding columns was just a matter of writing the sql and executing it. However, now that I'm working in Magento I want to do things "the Magento way".
Scenario: we use paypal express, and before the controller redirects to paypal, I would really like to add a field (if not there already) in sales_flat_quote, called paypal_status - and set the value = 1 (we'll call it, sent to paypal).
On return I want to update that to either 2 or 3 (returned and pending transaction, or returned and captured transaction).
So there are two things I need to know how to do:
have something like $db->addColumn('paypal_status') where it will only add if not exists, and
write UPDATE sales_flat_quote SET paypal_status = 1 WHERE entity_id =
{whatever}
This will be inside the ...Paypal_Express class.
Open database and fire this SQL: Alter table sales_flat_quote Add paypal_status tinyint(1) NOT NULL DEFAULT 1;
Alternatively, you can write following in your SQL file (located at CompanyName\MyModuleName\sql\companyname_modulename_setup) of your custom module. This file will get executed only one time , that is the first time when the module is installed. At that time your custom column will not be there in database so it will create one.
$installer = $this;
$installer->startSetup();
$installer->run("ALTER TABLE `{$installer->getTable('sales/quote')}` ADD `paypal_status` tinyint(1) NOT NULL DEFAULT 1 COMMENT 'My Custom Paypal Status';");
$installer->endSetup();
Clear all cahces.
To save data :
$myValue = 2;
Mage::getSingleton("checkout/cart")->getQuote()->setPaypalStatus($myValue)->save();
Mage::getSingleton("checkout/cart")->getQuote() will give you current quote.
In your sql file at CompanyName\MyModuleName\sql\companyname_modulename_setup copy the following code in order to create the column.
$installer = $this;
$installer->startSetup();
$installer->getConnection()
->addColumn($installer->getTable('sales/quote'),
'paypal_status',
array(
'type' => Varien_Db_Ddl_Table::TYPE_INTEGER,
'nullable' => true,
'comment' => 'Paypal Status',
)
);
$installer->endSetup();
Logout and login, and flush magento cache in order to add the column to the table.
The Express Checkout controller is in app/code/core/Mage/Paypal/Controller/Express/Abstract.php. If you want to add a field before the controller redirects to paypal you can modify the _initCheckout() method like this:
protected function _initCheckout()
$quote = $this->_getQuote();
if (!$quote->hasItems() || $quote->getHasError()) {
$this->getResponse()->setHeader('HTTP/1.1','403 Forbidden');
Mage::throwException(Mage::helper('paypal')->__('Unable to initialize Express Checkout.'));
}
$quote->setPaymentStatus(1); // Here is your change
$this->_checkout = Mage::getSingleton($this->_checkoutType, array(
'config' => $this->_config,
'quote' => $quote,
));
return $this->_checkout;
}
I have a cakePHP problem - I want to make a update query like this
UPDATE table SET field = field + some_var
and I don't know how to do it...
Can anyone help me?
The only "right" way would be using cake's "atomic query" wrapper methods. In your case that would be "updateAll".
The question is a complete duplicate of a dozen other questions - like Incrementing Cakephp database field by a value
$var = 1;
$this->Article->updateAll(
array('Article.viewed' => 'Article.viewed + ' . $var),
array('Article.id' => $id)
);
This is also in the docs: http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions
There are two ways to do an update:
If you are only updating one field you can do:
$this->Model->id = foo;
$this->Model->saveField('field_name', 'field_value');
or, you can do an update using $this->Model->save():
$data = array(
'Model'=>array(
'id'=>foo,
'field_name'=>'field_value',
'another_field_name'=>'another_field_value'
)
);
$this->Model->save($data);
You want to avoid using $this->Model->query() and use CakePHP's built in methods because the build in methods are datasource agnostic (they work the same on MySQL, Oracle, MSSQL etc.)
You can use the callback method beforeSave to implement what you need.
Callback Method: BeforeSave
public function beforeSave($options = array()) {
if (!empty($this->data['table']['field'])){
$this->data['table']['field'] += $this->data['table']['some_var'];
}
return true;
}
I think the best method is using the Model::updateAll(array $fields, array $conditions).
The Model::saveField(string $fieldName, string $fieldValue, $validate = false) this method when you try to update using same primary key it shows cannot replace duplicate key error. And think when one updates they must be using the primary key as a matching value to update value.
Use
$this->Baker->updateAll(
array('Baker.approved' => 'Baker.approved + ' . $some_var),
array('Baker.id' => $someId)
);
For more information see: http://book.cakephp.org/2.0/en/models/saving-your-data.html