i want to insert data an array, from array format like this with codeigniter frameworks.
Array ( [run_date] => Array ( [0] => 2015-06-15 11:10 [1] => 2015-06-15 11:10 [2] => 2015-06-15 11:10 [3] => 2015-06-15 11:10 ) [msisdn] => Array ( [0] => 8499270093 [1] => 8599387282 [2] => 6281019183 [3] => 8597375112 ) )
i've been trying to use insert_batch command on codeigniter but it's not works at all. such like below.
My Controller
function insertFromConfirmation() {
$datanew = array(
'run_date' => $this->input->post('run_date'),
'msisdn' => $this->input->post('msisdn')
);
print_r($datanew);
$this->modelMsisdn->insertDataArray($datanew);
}
and My Model
public function insertDataArray($datanew) {
$this->db->insert_batch('subscription_renewal', $datanew);
}
Error Shown:
Error Number: 1054 Unknown column '0' in 'field list' INSERT INTO `subscription_renewal` (`0`, `1`, `2`, `3`) VALUES ('2015-06-15 11:10','2015-06-15 11:10','2015-06-15 11:10','2015-06-15 11:10'), ('8499270093','8599387282','6281019183','8597375112')
Filename: C:\xampp\htdocs\msisdn_tools_new\system\database\DB_driver.php Line Number: 330
Table Structure
CREATE TABLE subscription_renewal (
id int(11) NOT NULL AUTO_INCREMENT,
msisdn varchar(32) CHARACTER SET utf8 NOT NULL,
service varchar(64) CHARACTER SET utf8 NOT NULL,
adn varchar(8) CHARACTER SET utf8 NOT NULL,
operator varchar(32) CHARACTER SET utf8 NOT NULL,
channel varchar(16) CHARACTER SET utf8 NOT NULL,
status tinyint(4) NOT NULL,
description varchar(20) CHARACTER SET utf8 DEFAULT NULL,
blacklist_status tinyint(4) NOT NULL,
date_created datetime NOT NULL,
date_modified datetime NOT NULL,
run_date datetime DEFAULT NULL,
price varchar(30) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=476 DEFAULT CHARSET=latin1
Insert batch array structure looking incorrect, you should pass input data into set array of each row... see sample array structure
$run_date = $this->input->post('run_date');
$msisdn = $this->input->post('msisdn');
$datanew = array();
foreach($run_date as $k => $v){
$datanew[] = array(
'run_date' => $v,
'msisdn' => $msisdn[$i] //suppose $msisdn[] have also same key length as $run_date[] array
);
}
$this->modelMsisdn->insertDataArray($datanew);
Related
I have the following tables.
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
group_id INT(11) NOT NULL,
username VARCHAR(255) NOT NULL,
name VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
email VARCHAR(255) NOT NULL,
lastlogin DATETIME DEFAULT NULL,
published BOOLEAN DEFAULT TRUE,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL,
UNIQUE KEY (username)
);
CREATE TABLE companies (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL,
UNIQUE KEY (name)
);
CREATE TABLE locations (
id INT AUTO_INCREMENT PRIMARY KEY,
company_id INT(11) NOT NULL,
uuid BINARY(36) NOT NULL,
name VARCHAR(255) NOT NULL,
clock_id INT(11) NOT NULL,
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL,
FOREIGN KEY location_company_key (company_id) REFERENCES companies(id),
);
Now I want to select all locations that are listed under the companies that are assigned to the logged in user;
$companies = $this->Locations->Companies->find()
->select(['Companies.id'])
->matching('Users', function ($q) {
return $q->where(['Users.id' => $this->Auth->User('id')]);
});
$locations = $this->Locations->find()
->where(['company_id IN' => $companies]);
But for some reason I don't get the expected result. Anybody an idea how to fix?
My code was correct, I hadn't had the right sample values in the database
$companies = $this->Locations->Companies->find()
->select(['Companies.id'])
->matching('Users', function ($q) {
return $q->where(['Users.id' => $this->Auth->User('id')]);
});
$locations = $this->Locations->find()
->where(['company_id IN' => $companies])
->contain(['Companies']);
I have two Tables:
it is defined as follow:
CREATE TABLE IF NOT EXISTS `users_correlations` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`correlated_id` int(11) NOT NULL,
`type` char(1) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;
CREATE TABLE IF NOT EXISTS `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`username` varchar(100) NOT NULL,
`first_name` varchar(50) NOT NULL,
`last_name` varchar(50) NOT NULL,
`password` varchar(100) NOT NULL,
`role` varchar(2) NOT NULL,
`gender` char(1) NOT NULL,
`dob` date DEFAULT NULL,
`location` varchar(100) NOT NULL,
`photo` varchar(255) NOT NULL,
`photo_dir` varchar(255) NOT NULL,
`about_me` tinytext,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`modified` datetime NOT NULL,
`follower_count` INT DEFAULT 0,
`following_count` INT DEFAULT 0,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=42 ;
Now i defined HABTM association as follow:
public $hasAndBelongsToMany=array(
'Following'=>array(
'className'=>'User',
'joinTable'=>'users_correlations',
'ForeignKey'=>'correlated_id',
'associationForeignKey' => 'user_id'
),
'Followers'=>array(
'className'=>'User',
'joinTable'=>'users_correlations',
'ForeignKey'=>'user_id',
'associationForeignKey' => 'correlated_id'
)
);
Now i want to implemnt Countercache to track record of number of followers and following..
I use ConterCacheHabtm behavior for my model referred by
http://bakery.cakephp.org/articles/danaki/2009/05/29/counter-cache-behavior-for-habtm-relations
but for my association it is not updating my follower_count and following_count.
Please Help in this scenario.
'Followers'=>array(
'className'=>'User',
'joinTable'=>'users_correlations',
'ForeignKey'=>'user_id',
'associationForeignKey' => 'correlated_id',
'counterCache' => true
)
You need to add the 'counterCache' => true to the array. The rest looks like it should work fine.
Say I have an object-like data record like this:
$article = array(
'title' => '',
'tagline' => '',
'content' => '',
'stats' => array(
'words' => 0,
'paragraphs' => 0,
'tables' => 0
),
'references' => array(
'reference 1',
'reference 2',
'reference 3'
),
'attachments' => array(
'images' => array(
'image 1',
'image s'
),
'videos' => array(
'video 1',
'video 2'
)
)
);
My question is how can I store this array of data record in relational database? How should I design the table structure?
I know I can always set up flat fields such as stats_words, stats_paragraphs, and so forth but is there any more structural ways? Instead of storing a JSON or serialized string in a single field....
Thanks!
For example this way:
article
ID
title _
tagline _
content ___
stat_words
stat_paragraphs
stat_tables
article_reference
ID
article_id -> article
reference _
article_attachment
ID
article_id -> article
att_type // image or video
path _
title _
(_ means varchar/text fields, other fields are numbers)
Or as MySQL DDL:
CREATE TABLE IF NOT EXISTS article (
id INT NOT NULL AUTO_INCREMENT,
title VARCHAR(255) NOT NULL,
tagline VARCHAR(255) NOT NULL,
content MEDIUMTEXT NOT NULL,
stat_words INT NOT NULL,
stat_paragraphs INT NOT NULL,
stat_tables INT NOT NULL,
PRIMARY KEY ( id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS article_reference (
id INT NOT NULL AUTO_INCREMENT,
article_id INT NOT NULL,
reference VARCHAR(255) NOT NULL,
PRIMARY KEY ( id ),
FOREIGN KEY ( article_id ) REFERENCES article( id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
CREATE TABLE IF NOT EXISTS article_attachment (
id INT NOT NULL AUTO_INCREMENT,
article_id INT NOT NULL,
att_type INT NOT NULL,
path VARCHAR(255) NOT NULL,
title VARCHAR(255) NOT NULL,
PRIMARY KEY ( id ),
FOREIGN KEY ( article_id ) REFERENCES article( id )
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
I have 2 basic models in my CakePHP application: User and Login. A user has a hasMany relation with Logins (i.e., a new login record is created everytime the user logs in).
Now, I want to make 2 relations from the User model to the Login model:
User hasMany Login
and
User hasOne lastLogin
This last relation should only include the last record of the Login model for the selected user.
I tried this as follows:
var $belongsTo = array
(
'LastLogin' => array
(
'className' => 'Login',
'order' => 'LastLogin.created DESC',
'limit' => 1
)
);
However, this doesn't work. Any ideas on how to get this working?
UPDATED ANSWER IN RESPONSE TO COMMENTS
With a belongsTo relationship, the foreign key should be in the current model.
This means that if you want to have a relationship where User belongsTo LastLogin, the users table should have a last_login_id field.
In your case you probably want to use a hasOne relationship instead, and you're going to have to use the MAX() SQL function in the fields key. Note that getting the last_login works completely independently of your User hasMany Login relationship. So if all you want is the last login you can remove the hasMany relationship and just leave the hasOne.
With the example code below you'll get this:
Output of /users/index:
Array
(
[User] => Array
(
[id] => 1
[name] => user1
[last_login] => 2011-05-01 14:00:00
)
[Login] => Array
(
[0] => Array
(
[id] => 1
[user_id] => 1
[created] => 2011-05-01 12:00:00
)
[1] => Array
(
[id] => 2
[user_id] => 1
[created] => 2011-05-01 13:00:00
)
[2] => Array
(
[id] => 3
[user_id] => 1
[created] => 2011-05-01 14:00:00
)
)
)
If you don't use the Model::afterFind() callback your results will look more like this (Login array snipped to save space):
Array
(
[User] => Array
(
[id] => 1
[name] => user1
)
[0] => Array
(
[last_login] => 2011-05-01 14:00:00
)
)
Example code:
users table:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
logins table:
CREATE TABLE `logins` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
User model:
class User extends AppModel {
var $name = 'User';
var $hasMany = array('Login');
var $hasOne = array(
'LastLogin' => array(
'className' => 'Login',
'fields' => array('MAX(LastLogin.created) as last_login')
)
);
// This takes the last_login field from the [0] keyed array and puts it into
// [User]. You could also put this into your AppModel and it would work for
// all find operations where you use an SQL function in the 'fields' key.
function afterFind($results, $primary=false) {
if (!empty($results)) {
foreach ($results as $i => $result) {
if (!empty($result[0])) { // If the [0] key exists in a result...
foreach ($result[0] as $key => $value) { // ...cycle through all its fields...
$results[$i][$this->alias][$key] = $value; // ...move them to the main result...
}
unset($results[$i][0]); // ...and finally remove the [0] array
}
}
}
return parent::afterFind($results, $primary=false); // Don't forget to call the parent::afterFind()
}
}
Users controller:
class UsersController extends AppController {
var $name = 'Users';
function index() {
$this->autoRender = false;
pr($this->User->find('all'));
}
}
I had a similar situation but mine was
Product hasMany Price
I wanted a Product hasOne CurrentPrice with the CurrentPrice defined as the top most record found if sorted by created in desc order.
I solved mine this way. But I am going to use your User and LastLogin instead.
class User extends AppModel {
var $name = 'User';
var $hasMany = array('Login');
var $hasOne = array(
'LastLogin' => array(
'className' => 'Login',
'order' => 'LastLogin.created DESC'
)
);
If you think about it, created and id has the same meaning. so you could also use id in descending order.
I am assuming that your table schema is similar to the one suggested by mtnorthrop.
i.e.
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
logins table:
CREATE TABLE `logins` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
Three simple tables...
Feedname (eg. News or
Events) which are the names of RSS
feeds.
Posts that belong to a
Feedname
User, that owns all
the posts
I want to use the Form helper to automatically give me a select box so that when I add a post I can select which Feedname to assign it to.
It seems like posts belong to both Feedname and User but I can't get the correct combination of belongsTo and hasMany in my model/ .php files. The select box for feedname is shown, but there is nothing in it. Can anyone point me in the right direction?
The tables look like this at the moment:
CREATE TABLE `feednames` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `posts` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
`body` text COLLATE utf8_unicode_ci,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
`user_id` int(10) unsigned NOT NULL DEFAULT '1',
`feedname_id` int(10) unsigned NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `foreign_key` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) CHARACTER SET latin1 NOT NULL,
`password` char(40) CHARACTER SET latin1 NOT NULL,
`group_id` int(11) NOT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
edit - adding the model .php files ...
class Feedname extends AppModel {
var $name = 'Feedname';
var $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'feedname_id',
'dependent' => false
)
);
}
class Post extends AppModel {
var $name = 'Post';
var $belongsTo = array(
'User' => array(
'className' => 'User',
'foreignKey' => 'user_id'
),
'Feedname' => array(
'foreignKey' => 'feedname_id'
)
);
}
class User extends AppModel {
var $name = 'User';
var $hasMany = array(
'Post' => array(
'className' => 'Post',
'foreignKey' => 'user_id',
'dependent' => false
)
);
}
edit - adding SQL dump ** ...
/posts/index.ctp:
SELECT COUNT(*) AS count FROM posts AS Post LEFT JOIN users AS User ON (Post.user_id = User.id) LEFT JOIN feednames AS Feedname ON (Post.feedname_id = Feedname.id) WHERE 1 = 1
SELECT Post.id, Post.title, Post.body, Post.created, Post.modified, Post.user_id, Post.feedname_id, User.id, User.username, User.password, User.group_id, User.created, User.modified, Feedname.id, Feedname.name, Feedname.created, Feedname.modified FROM posts AS Post LEFT JOIN users AS User ON (Post.user_id = User.id) LEFT JOIN feednames AS Feedname ON (Post.feedname_id = Feedname.id) WHERE 1 = 1 ORDER BY Post.created DESC LIMIT 10
Please note: /posts/add.ctp does not produce any SQL dump, so it's not getting the select box options from the database, this is what I'm trying to fix with proper model relationships.
Do you have something like this in your controller methods (e.g. the admin_add / admin_edit functions)?
$feednames = $this->Feedname->find('list');
$this->set('feednames', $feednames);
Cake should then automatically populate the select list with these values. Or you can manually set the values with:
$form->input('feedname_id', array('options' => $feednames));
So far I agree :
posts > belongs to > users
posts > belongs to > feednames
feednames > has many > posts
users > has many > posts
Just checking, but, did you actually insert data into your tables? Else it would be only logical that your select field is empty. Also, what does the Sql dump say in debug mode?