Yii : Save data to new table - php

I am new to yii and have a basic doubt.
I am working on an app where I have to store data submitted in one form into a new table.
As I know one table=one model
should I create a new model for the new table using gii?
Can't I just use the following code without creating the model in gii?
$modelA = new table_name;
$modelA->attributes = $_POST['table_name'];
$modelA->save();

No, you have to create model, because:
$modelA = new ModelClassName();
and not table name. You still may use relations for other tables, so you can have only one model:
$modelA->tableNameB->attributes = $_POST['attributes4B'];

Related

Laravel: Create or update related model?

Please be gentle with me - I'm a Laravel noob.
So currently, I loop through a load of users deciding whether I need to update a related model (UserLocation).
I've got as far as creating a UserLocation if it needs creating, and after a bit of fumbling, I've come up with the following;
$coords = $json->features[0]->geometry->coordinates;
$location = new UserLocation(['lat'=>$coords[1],'lng'=>$coords[0]]);
$user->location()->save($location);
My issue is that one the second time around, the Location may want updating and a row will already exist for that user.
Is this handled automatically, or do I need to do something different?
The code reads like it's creating a new row, so wouldn't handle the case of needing to update it?
Update - solution:
Thanks to Matthew, I've come up with the following solution;
$location = UserLocation::firstOrNew(['user_id'=>$user->id]);
$location->user_id = $user->id;
$location->lat = $coords[1];
$location->lng = $coords[0];
$location->save();
You should reference the Laravel API Docs. I don't think they mention these methods in the "regular docs" though so I understand why you may have not seen it.
You can use the models firstOrNew or firstOrCreate methods.
firstOrNew: Get the first record matching the attributes or instantiate
it.
firstOrCreate: Get the first record matching the attributes or create it.
For Example:
$model = SomeModel::firstOrNew(['model_id' => 4]);
In the above example, if a model with a model_id of 4 isn't found then it creates a new instance of SomeModel. Which you can then manipulate and later ->save(). If it is found, it is returned.
You can also use firstOrCreate, which instead of creating a new Model instance would insert the new model into the table immediately.
So in your instance:
$location = UserLocation::firstOrNew(['lat'=>$coords[1],'lng'=>$coords[0]]);
$location will either contain the existing model from the DB or a new instance with the attributes lat and lng set to $coords[1] and $coords[0] respectively, which you can then save or set more attribute values if needed.
Another example:
$location = UserLocation::firstOrCreate(['lat'=>$coords[1],'lng'=>$coords[0]]);
$location will either contain the existing model from the DB or a new model with the attributes set again, except this time the model will have already been written to the table if not found.

Silverstripe 3.1 - Can't create a new many_many relation

while extending the CsvBulkUploader to fit my needs, I cam across the problem, that Silverstripe doesn't let me create a new entry for a many_many relation.
My dataobject is ShopItems and has a many_many relation called Visuals. So in my MySQL database I get ShopItems_Visuals.
Now I want to create a new entry for this with the following code, and I think here's the place I made some mistake.
...
$visual = ShopItem_Visuals::create();
$visual->ImageID = $file->ID;
$visual->ShopItemID = $obj->ID;
$visual->write();
...
after adding this to my function, I receive Class 'ShopItem_Visuals' not found after hitting the import button.
Is that because the database Table was created through the many_many relation in ShopItem and has no ClassName itself?
Can someone tell me how to create a new entry for this relation?
Thank you in advance.
I don't think that there's a Class for the mapping table itself.
The entry in it should be created automagically, when adding a related Object via add.
$visual = new Visual();
...
$visual->write();
$ShoptItem->Visuals()->add($visual);
$ShoptItem->write();
If the many-many-relation name is Visuals, calling ->Visuals() should return an instance of ManyManyList on which you can call add, remove etc.
see http://api.silverstripe.org/3.0/class-ManyManyList.html

Get mysql table field names in ZF2

I want to store the csv data dynamically into mysql table. According to my csv columns header i want to insert the data into respective columns in mysql table. For this, I need to get all the table fields name from Zend Framework Controller or Model.
I have tried with:
**
$metadata = new Zend\Db\Metadata\Metadata($adapter);
$table = $metadata->getTable($tableName);
$table->getColumns();
**
But, it shows the error:
Fatal error: Class 'Import\Model\Zend\Db\Metadata\Metadata' not found.
How can I get all the mysql table fields name using Zend Framework 2?
you have to use a backslash before zend
correct one :
$metadata = new \Zend\Db\Metadata\Metadata($adapter);
You can also use the use-statement at the top of your file.
namespace Import\Model;
use Zend;
Or you use the following:
namespace Import\Model;
use Zend\Db\Metadata\Metadata;
// ... lots of code here ;-)
$metadata = new Metadata($adapter);
At Header section
namespace Import\Model;
use Zend\Db\Metadata\Metadata;
In Modal function
$metadata = new Metadata($adapter);
$fields=$metadata->getColumnNames($table);
Instead of creating new instance of Metadata (its depricated), you should use the factory for this
use Zend\Db\Metadata\Source\Factory;
$metadata = Factory::createSourceFromAdapter($adapter);

YII model to handle more than one table

I am developing a registration form in YII. In my form there is a radio option to choose register as Mode1 or register as Mode2. If user chooses mode1, data's should be entered to table1 or it should entered to table2.
In YII each model deals with one table. Here my form deals with two tables.
So how to handle such a form to validate and enter data's to table in YII?
The easiest way is to create one model for the form (assuming they have the same fields?)
This class would extend CFormModel (in the example below I refer to this model as GlobalFormModel)
This model would have the same attributes as the other two models, as well as one new attribute called mode
When the form is submitted, in the controller you can handle it based on which mode and validate it against the correct model, eg:
$model = new GlobalFormModel
if(isset($_POST['GlobalFormModel'])){
$model->attributes = $_POST['GlobalFormModel'];
if ($model->mode == 1){
$newmodel = new FormOne;
$newmodel->attributes = $model->attributes;
} else {
$newmodel = new FormTwo;
$newmodel->attributes = $model->attributes;
}
... // validate and save $newmodel
}
$this->render("yourview",array("model"=>$model));
Where FormOne is the model associated with the first table, and FormTwo is associated with the second table. First you create a new instance of the GlobalFormModel (which is passed to the view). You check if the form has been submitted (you could validate it here or after loading one of the two models, that is your choice). You check the mode, and then load the correct model.

Copy a model to another database in symfony 1.4

Using Symfony 1.4 and doctrine I'd like to save a retrieved model to a different database connection:
retrieve model from master-database
change database connection to slave-database
save the model to the slave-database
I have the 2 connections defined in databases.yml.
here in pseudo-code:
$model = [retrieved from master-database];
$slaveConnection = Doctrine_Manager::getInstance()
->getConnection('slave-connection');
$model->save($slaveConnection);
If I create a new model, $model=new model(); the "code" above successfully saves the model to the slave-connection.
What is going wrong?
According to the Symfony log, Symfony recognizes the model as existing and issues an update (instead of an insert).
UPDATE model SET updated_at = '2011-10-21 17:37:32' WHERE id = '1';
Although Symfony is using the correct database connection ('slave-connection'), the update fails because the model isn't present in the slave-database, yet.
And the insert into the slave-database should use all values of the model, not only the changed ones, too.
Anyone can point me to the right direction to save an existing model to a different database?
edit with my solution.
Thanks samura!
Just some additions:
After performing deep copy Symfony saved a new id. But I wanted to really clone the model object to the slave db and so, I had to modify the id.
That caused unique constraint exceptions, so I had to delete first. So this is it:
$id = $model->getId();
$slaveConnection->execute("delete from modeltable where id=".$id);
$model_copy = $model->copy(true); # deep copy
$model_copy->setId($id);
$model_copy->save($slaveConnection);
hope this helps if someone else stumbles.
You could use the public function copy($deep = false) method of the Doctrine_Record class.
$model = [retrieved from master-database];
$slaveConnection = Doctrine_Manager::getInstance()
->getConnection('slave-connection');
$model_copy = $model->copy(true); # deep copy
$model_copy->save($slaveConnection);

Categories