Saving Array to Database in CakePHP
I'm out of ideas here is my controller:
class GoogleNewsController extends AppController {
var $name = 'GoogleNews';
var $uses = array('GoogleNews', 'SavedNews');
var $helpers = array('Html','Form');
function index() {
$saved = $this->set('news',$this->GoogleNews->find('al开发者_如何学编程l'));
Im reading data from 'GoogleNews' and they are in my array. Array looks like this:
array(10) {
[0]=>
array(1) {
["GoogleNews"]=>
array(12) {
["title"]=>
string(32) "FIFA 11 für 25,49€ aus Jersey"
["link"]=>
string(54) "http://feedproxy.google.com/~r/myDealZ/~3/HuNxRhQJraQ/"
["pubDate"]=>
string(31) "Mon, 06 Dec 2010 10:53:22 +0000"
["creator"]=>
string(5) "admin"
["guid"]=>
array(2) {
["value"]=>
string(30) "http://www.mydealz.de/?p=15137"
["isPermaLink"]=>
string(5) "false"
}
["description"]=>
string(355) "
And I want to save elements to my database 'SavedNews' I need to save description and title. Can anybody tell me how should I write it?
$this->SavedNews->set(array('description' =>$this->GoogleNews->find('description')));
Is this a solution? Its only way that it works, but it puts null values to my columns.
If I'm understanding your requirements correctly, the following should work.
In your controller:
class NewsController extends AppController
{
function import_from_google()
{
// Load the GoogleNews model and retrieve a set of its records
$this->loadModel('GoogleNews');
$newsFromGoogle = $this->GoogleNews->find('all');
$this->loadModel('SavedNews');
foreach ($newsFromGoogle as $_one) {
// Reset the SavedNews model in preparation for an iterated save
$this->SavedNews->create();
// Assemble an array of input data appropriate for Model::save()
// from the current GoogleNews row
$saveable = array(
'SavedNews' => array(
'title' => $_one['GoogleNews']['title'],
'description' => $_one['GoogleNews']['description']
)
);
// send the array off to the model to be saved
$this->SavedNews->save($saveable);
}
$this->autoRender = false; // No need to render a view
}
}
Refine as desired/required. For example, the iterated save operations should happen in the SavedNews model, rather than in the controller. The above code also has no fault-tolerance.
HTH.
精彩评论