Auto generating a value during update - sql-server

I am using ef-core 2.1 with MSSQL, in OnModelCreating I use the following which auto populates a created field correctly:
modelBuilder
.Entity<MyModel>()
.Property(e => e.Created)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnAdd()
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
Additionally, I want to populate (and update thereafter) another field as follows:
modelBuilder
.Entity<MyModel>()
.Property(e => e.Modified)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnUpdate()
.Metadata.ValueGenerated = ValueGenerated.OnUpdate;
However, this has no effect. In reading value-generated-on-add-or-update it is not clear to me if no facility exists to support this and a trigger is the only option or I simply have the configuration wrong.
The fluent method calls appear to support this, anyone know what I am doing wrong?

Hmm, I am not real familiar with what you are trying with .Metadata.ValueGenerated, however, I am doing something very similar in my project with success (note that my db is MySQL).
Maybe try like below.
modelBuilder
.Entity<MyModel>()
.Property(e => e.Modified)
.HasDefaultValueSql("GETUTCDATE()")
.ValueGeneratedOnAddOrUpdate();

Related

What's going wrong with my migrations on CakePHP 4?

I've applied a couple of minor changes to the database structure for my app, adding new columns to a table called Plots. This is one of the migrations -
declare(strict_types=1);
use Migrations\AbstractMigration;
class AddGarageToPlots extends AbstractMigration
{
public function change()
{
$table = $this->table('plots');
$table->addColumn('garage', 'string', [
'default' => null,
'limit' => 255,
'null' => true,
]);
$table->update();
}
}
When I apply the migration it seems to run fine: there are no errors and I can see the new column in the database if I connect directly to it but when I try to access data in the new field in a view using, for example, <?= $plot->garage ?> it consistently returns null even though I have populated this field via the direct connection.
Is there something else I need to do that I'm missing here or is there some way I can check that the migration has worked properly like a schema file somewhere?
Found the answer to my own question by reading slightly further in the documentation - migrations and deployment.
I needed to run bin/cake schema_cache clear

Query limitation in DBO (Joomla 3.8.1)

I use JDatabaseDriver for interaction with database.
The next code I took from official Joomla Documentation.
Documentation
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
$query
->select($db->quoteName(array('user_id', 'profile_key', 'profile_value', 'ordering')))
->from($db->quoteName('#__user_profiles'))
->setLimit('10');
Look at the last row in code above.
The setlimit method is no exist in JDatabaseDriver class but it is declared in class - JDatabaseQueryMysqli.
Don't I understand the logic or there is some mistake?
In Latest Joomla 3.8.1 setLIMIT does not work properly. You may go for alternative methods like
$query->setQuery($query,start,offset);

CakePHP: Scaffolding after having written edit/view/add

I have an application in which we give a very friendly interface for managing data. This is done through many controllers' add/edit/view functions. But now the requirement has come that we should have "super admins" able to edit anything, and scaffolding will give them a quick and dirty manner of changing data. Since scaffolding uses add/edit/view by default, I've unintentionally overwritten the ability to scaffold.
I can't just go and change all my calls to edit/add for our "user friendly" data managing. So I want to essentially ignore the add/edit/view when, for example, a user has a flag of "yes, please let me scaffold". I imagined it would be something like:
public function edit($id) {
if (admin_user) {
$scaffold;
} else {
[user-friendly version code]
}
}
But no dice. How can I achieve what I want?
suppose you already have admin users and you want to scaffold only super-user:
Also suppose you store the information about beeing a super-user or not in a column named super in the users table
in your core.php
Configure::write('Routing.prefixes', array('admin', 'super));
in your appController
public $scaffold = 'super';
beforFilter() {
if($this->Auth->user('super') && !isset($this->params['super'])
$this->redirect(array('super' => true));
}
Now I can't try this code but the idea should work.
edit: we need to check if we are already in a super_action to avoid infinite redirect

CakePHP read() is not returning a model name

I am having trouble with my cakePHP and wondering if anyone else has experienced this. I am trying to setup a User object. I create the Model:
class User extends AppModel
{
}
I create the controller:
class UsersController extends AppController
{
function view($id = null) {
$this->User->id = $id;
$this->set('users', $this->User->read());
}
}
and I go to the view page. However, I am not getting what the cake documentation says I should be getting. I am getting:
Array
(
[0] => Array
(
[id] => 3
[FirstName] => 1
[LastName] => 1
)
)
when what I am expecting to see is
Array
(
[User] => Array
(
[id] => 3
[FirstName] => 1
[LastName] => 1
)
)
Also when I do a $this->User->find('all'); I get back an array like so:
Array
(
[0] => Array ([0] => Array (/*stuff here*/))
[1] => Array ([0] => Array (/*stuff here*/))
[2] => Array ([0] => Array (/*stuff here*/))
)
I have tried changing the name to Myuser (including the database table, controller, model, etc) and still have the same results, so I don't think it's related to a reserved keyword.
Has anyone run into this or, more importantly, does anyone have a clue how I might fix it? Thanks.
EDIT:
I am using cake version 2.0.6. I am using a MySQL 5.0.92 database. I just have tried setting the name variable and it did not change my results.
After an ENTIRE DAY of troubleshooting, I finally was able to solve it.
The cause is definitely an outdated pdo_mysql.so library. This is located in /usr/local/lib/php/extensions/(latest directory)/pdo_mysql.so
The table name being returned in getColumnMeta was only added in a certain version due to this function request:
https://bugs.php.net/41416/
Now, the problem is, in some web hosts, PHP needs to be compiled with Easy Apache. Mine had to go through that as well just in order to enable PDO (it was initially disabled). But the problem is, for some reason, Easy Apache is downloading some obsolete source code everytime it runs. Running yum or installing any RPMs don't help either.
So here is what I did:
- I downloaded the latest PHP sources from the PHP site, extracted the tarball
- I ran Easy Apache, did a recompilation, and very quickly went to the console to watch it redownload the outdated PHP sources
- When the PHP sources have reappeared, I very quickly replaced the entire ext/pdo_mysql directory with the latest sources
- Easy Apache will compile httpd first, so you have some time to do the above step
- After the build is done, reboot.
- To check if your version of pdo_mysql.so supports the table name, execute this command:
strings -f pdo_mysql.so | grep ': table'
- There should be an entry there. The old version doesn't.
- By the way, I noticed that there are more copied of the pdo_mysql.so in /usr/lib/php/modules and /usr/lib/php/extensions, but it seems that the one in /usr/local is the one that is active. Nevertheless, I update all copies manually
NOTE: if you just try to update the pdo_mysql.so file, it will not work. You will get a segmentation fault, and the pages will render nothing. You need to recompile PHP using the above steps.
I hope this will help other people who will come across this bug.
Be sure your table is named users and include the association explicitly
class User extends AppModel {
public $name = 'User';
public $useTable = 'users';
...
You need to set the $uses variable to associate the User model with the controller if you are using any additional models. Adding it explicitly even if there's just one will not hurt either...
for example
class UsersController extends AppController {
//Controller Name
public $name = 'Users';
//DB Config for desired connection
public $useDbConfig = 'test';
// Array of associated models
public $uses = array('Store','User');
//Array of Helpers used by Controller Views
public $helpers = array('Html', 'Form');
...
Also, check to be sure there are no edits in AppModel or AppController which may be accidentally contributing to the interactions here... You may also consider dumping the value of the $uses to see what's there.
Finally found out that the reason for it has to do with a function called PDOStatement::getColumnMeta. This gets called on the queries that cakePHP runs is used by the framework to get the column name, column type, and table name. However, for whatever reason, on the webhost I currently have, this function does not return the table name so cakePHP defaults to creating the array with a 0 index rather than a table name index.
$column = $results->getColumnMeta($index);
if (!empty($column['table']) && strpos($column['name'], $this->virtualFieldSeparator) === false) {
$this->map[$index++] = array($column['table'], $column['name'], $type);
} else {
$this->map[$index++] = array(0, $column['name'], $type);
}
still not sure how to fix it yet, but this is definitely why it is happening.
Yes, you are right. beastmaster
The reason why is that u using old version of PDO driver which has been been deprecated. the PDOStatement::getColumnMeta does not show [table]=name in old version
So solution here download new version of PHP which has build-in PDO. DO NOT INSTALL PDO VIA PECL coz u getting old version of PDO extension. and using
<?php phpinfo ?>
to check if it is installed properly. so u can use native PDO driver coming with PHP rather than use extension PDO driver.
By the way, Thank you for point out the problem.
I have just faced the problem. The cause was not an outdated pdo_mysql.so library.
If you use cakephp 2.3.x and make sure to use PHP 5.2.8 or greater, you should check whether the pdo_mysql extension is enabled or disabled.
You can echo phpinfo() to check it.
Note: the pdo_mysql extension is only enabled if you see "PDO Driver for MySQL enabled", otherwise it is disabled.

ACL retrieve alias in AROS table?

So I finally got "ACL" to work, and now im trying to get the "alias" value from the "AROS" table.
I want to make a simple message like logged in as .... (admin, moderator or user).
After some tinkering i got the "alias" value from the code below but I can't shed the feeling ther's an easier way to do this. Any help or advice will be greatly appreciated.
Currently im using:
$logindata = $this->Acl->Aro->findByForeignKey($user['User']['id']);
$parent_id = $logindata['Aro']['parent_id'];
$rankdata = $this->Acl->Aro->find('first', array('recursive' => -1, 'conditions' => array('Aro.id' => $parent_id)));
$rank = $rankdata['Aro']['alias'];
There are two option for you which is simpler than yours..i tried that in my project.
1.Save your aros with the same alias as its parent.And then you can use it simply with one line code.
2.Or you can save its parent alias into users table and then you get this all again almost every part of your site with $auth .

Resources