In python::Pylons i'm able to issue a setup-app command and it will look at my Models and issue the appropriate CREATE TABLE or CREATE INDEX ddl for my particular database.
it seems like this would be a feature in CakePHP, but i'm having trouble finding it.
in fact i see this in the manual:
"You can create your database tables as you normally would. When you create your Model classes, they'll automatically map to the tables that you've created."
which leads me to believe it doesn't exist?
No, it's other way around - you can create models, controllers and views by having DB schema. It's more logical to have a DB design schema first.
Check this out
Some of the comments in the accepted answer above lead me to creating this answer. You can technically create new tables on the fly using the YourModel->query() function. I am currently using this in a Behavior I am writing. This works in CakePHP 2.x, pretty sure it works in 1.3 as well.
In the setup function for the Behavior I am checking to see if the table already exists. If it doesn't I create it.
$dataSource = ConnectionManager::getDataSource('your DB');
if(!in_array($tableName, $dataSource->listSources()){
$this->createYourTableFunction();
}
In the createYourTableFunction you create a temporary model to run the YourModel->query() against. And just provide it your SQL instructions. When creating your temporary model just set the table parameter to false so you don't get a missing table error.
$YourModel = new Model(array('table' => false, 'name' => 'YourModel', 'ds' => 'Your DB'));
$YourModel->query('SQL instruction string');
Related
Yesterday I asked this question about changing the name of the __Migration History table generated by Entity Framework when using a Code First approach. The provided link was helpful in saying how to do what we want (and by "want" I mean what we're being forced into by our DBAs), however also left a somewhat non-specific and dire-sounding warning that says,
Words of precaution
Changing the migration history table is powerful but you need to be
careful to not overdo it. EF runtime currently does not check whether
the customized migrations history table is compatible with the
runtime. If it is not your application may break at runtime or behave
in unpredictable ways. This is even more important if you use multiple
contexts per database in which case multiple contexts can use the same
migration history table to store information about migrations.
We tried to use this warning to reason with the DBA team, telling them that we shouldn't mess with things because "here be dragons". Their response was, "It sounds more like the danger is in changing the content or the table structure, not the name. Go ahead and try it and see what happens."
Has anyone here changed the name of the __Migrations History table, and what was the result? Is it dangerous?
Changing the name of the migrations history table is possible.
But you have to tell EF this by calling the HasDefaultSchema method with the name of the schema in the OnModelCreating method of your DbContext class:
public partial class CustomerDatabasesModel : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("CustomerDatabases");
// Fluent API configuration
}
}
This the will cause EF to create a "CustomerDatabases" prefix for all database tables.
So in this example "CustomerDatabases" replaces the standard of "dbo" prefix of your tables. Your migration history table will be have the name CustomerDatabases.__MigrationHistory.
So in fact, you change the owner name of the database (the first part), the second part "__MigrationHistory" stays the same.
Usage scenario:
You usually do this, if you work with more than one DbContext.
So you can have more than one MigrationHistory table in a single database, one for each context.
Of cause you should carefully test this and perform database backups before.
Please check out this answer too:
Entity-Framework: On Database, multiple DbContexts
I am a newbie to cakephp and could really use some help and suggestions!
the application I am working with currently interacts with two databases, both databases have more or less a similar schema and table structure, I have to save some information in both databases, so i have this table say "employee_information" in both databases, both tables have a set of common fields (first_name, last_name, birthday, gender etc) and some other fields specific to that database.
now i have to save some information into the other database using cakephp model::save() method, previously I was normally switching data source and would use sql INSERT to do this and it was working fine, but now i really would like using cakephp conventional methods to do this, reason is that i think i am missing a great deal by not using cake's own methods ( data sanitizing in my case)
i had tried switching data source and using model::save(), the method did not work, though it did not log any errors, but also did not add any record into the database.
// using following snippet in the model to save.
$this->setDataSource('secondary_database');
$this->save($this->data);
$this->setDataSource('primary_database');
Any ideas or suggestions would be highly appreciated!
Thanks!
You're almost there, but you need to setup two db configs and select them with useDbConfig
For example:
$this->User->save($this->data); //Saves data to default (first) database
$this->User->useDbConfig('second'); //Selects second database for next uses
$this->User->save($this->data); //Saves data to second database too
//$this->User->useDbConfig('default'); //Not needed unless you want to do staff with the default database again later in the same code.
But if I'd need to save different fields in each DB, then I'd go with different models.
Setting custom table for the controller after switching data source worked for me. (http://api.cakephp.org/1.3/class-Model.html#_setSource)
$this->User->setDataSource('secondary_database');
$this->User->setSource('secondary_database_table');
$this->User->save($this->data,array(
'validate' => true,
'fieldList' => $fieldList // specific fields that needs to be updated.
));
I need to store data's change histories in database. For example some time some user modify some property of some data. The expected result is we can get the change histories for one data like
Tom changed title to 'Title one;'
James changed name to 'New name'
Steve added new_tag 'tag23'
Based on these change histories we can get all versions for some data.
Any good idea to achieve this? Not limited to traditional relation database.
These are commonly called audit tables. How I generally manage this is using triggers on the database. For every insert/update from a source table the trigger copies the data into another table called the same table name with an _AUDIT appended to it (the naming convention does not matter, it's just what I use). ORACLE provides you with something called journal tables. Using ORACLE designer (or manually) you can achieve the same thing and often developers put a _JN to the end of the journal/audit table. This, however, works the same, with triggers on the source table copying data into the audit table.
EDIT:
I should also note that you can create a new separate schema to manage just your audit tables or you can keep them in your schema with the source tables. I do both, it just depends on the situation.
I wrote an article about various options: http://blog.schauderhaft.de/2009/11/29/versioned-data/
If you are not tied to a relational database, there are things called 'append only' databases (I think), which never change data, but only append new versions. For your case this sounds kind of perfect. Unfortunately I don't know of any implementation.
I have a database table and I want to load it to model? Not by specified condition but whole table. How to do it?
models in ATK4 are used to represent data and to abstract the underlying technicalities but not directly hold them.
it is used by MVCGrid, MVCForm and CRUD to know how data is to be presented / laid out to the user's interface.
though models may not hold data, they are used to retrieve it through dsql.
example:
$m = $this->add('Model_UserAccess');
$u = $m->dsql()
->field('usernm')
->field('acclvl')
//->do_getOne(); // return only 1 record
->do_getAll(); // return all records
the use of DSQL or Dynamic SQL is important
to retrieve data from tables and save it back.
I have a very simple script that creates the necessary .php files to copy to /lib/Model.
I did it because was migrating an Access application with tables of 20-30 attributes and was very tedious to create it by hand.
The script it's very very basic, but it's very useful for me.
Here is the link
https://github.com/ajmmartinez/atk4_create_mod
Try
$data = $mymodel->getRows();
This will get all the data from the model and store into the array. Your question is difficult to understand, so I'm not sure how to reply.
Does any one know how to create a view from hibernate with the results of a criteria query?
We've got some legacy parts of our application that use views generated by the app for data retrieval and I like to tie the new NHibernate stuff into those for minimal friction.
I'd turn it into an extension method so I could eventually do stuff like this:
session.CreateCriteria<Thing>().CreateReportView().List();
Any ideas?
The existing process is like this:
SQLString = _bstr_t("SELECT name FROM User WHERE Retired = false");
...run the query process the results, then...
SQLStringView = _bstr_t(" \
BEGIN EXECUTE IMMEDIATE 'CREATE OR REPLACE VIEW ") + ViewName + _bstr_t(" AS ") + SQLString;
So whenever we run this query we get a view that has the same data in it. I can't work out how to replicate this is hibernate though.
To create a view using NHibernate directly, take a look at the 'database-object' mapping element.
Ayende has a good example here.
Check out this article for an explanation of mapping an entity class to a view and a table. I'm not certain that you'll be able to dynamically create your views at runtime as you specified; but perhaps this can be done as part of the schema generation process using the database-object mapping?
If you're only interested in filtering the data being returned, you may want to have a look at Nhibernate's filtering mechanisms; here is a good article outlining their usage.