CakePHP HABTM Duplication Issue - mysql

I am having an issue with CakePHP 1.3 and a HABTM relationship. I have 2 models, Offer and Device. An Offer can be on multiple Devices, and a Device has multiple Offers. I have an devices_offer.php model and join table. What is happening is when an Offer is Edited, it creates a 2nd, unfinished entry, which contains the edit in both the offers table and the join table. The original Offer stays the same. Another thing is, an Offer also has a relationship with a Business (model). A Business owns an offer. The reason I say this, is the duplicate Offer entry that is created when editing an Offer does NOT contain the business name in the entry. So I'm wondering if this relationship is messing something up...Also, When a Device is edited, It duplicates ALL the offers that are related to the device, AND keeps the old ones. The code is really nothing more than baked controllers, and I followed the CakePHP docs to create the HABTM:
offers_controller.php (edit function):
if ($this->Offer->save($this->data)) {
$this->Session->setFlash(__('The offer has been saved',true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The offer could not be saved. Please, try again.',true));
}
devicesOffer contains:
var $belongsTo = array('Device' => array(
'className' => 'Device',
'foreignKey' => 'device_id',
'conditions' => '',
'fields' => '',
'order' => ''),
'Offer' => array(
'className' => 'Offer',
'foreignKey' => 'offer_id',
'conditions' => '',
'fields' => '',
'order' => ''
));
Offer Model:
var $hasAndBelongsToMany = array(
'Device' => array(
'className' => 'Device',
'joinTable' => 'devices_offers',
'foreignKey' => 'offer_id',
'associationForeignKey' => 'device_id',
'unique' => true,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => '',
'with' => 'DevicesOffer'
)
);
Device Model:
var $hasAndBelongsToMany = array(
'Offer' => array(
'className' => 'Offer',
'joinTable' => 'devices_offers',
'foreignKey' => 'device_id',
'associationForeignKey' => 'offer_id',
'unique' => true,
'conditions' => 'Offer.active = 1 AND Offer.expires > now()',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'finderQuery' => '',
'deleteQuery' => '',
'insertQuery' => ''
)
);
UPDATE
I have Offers now editing / saving correctly. However, when I update / edit a Device. All the offers related to that device are duplicated ONLY in devices_offer. I am assuming this is because the ID's are not there. However, how would I set the ID's of the offers that are related to the device when saving??

Related

Copy values from one database to another using laravel

I'm using two different databases, one called "example" and another "example_hist". I'm trying to create a cron job that verifies the database "example" in table "users" if there is any user that has a state "disabled".
If there is, it should copy the user row to the table "users" inside the database "example_hist"
My problem is that I can't figure out how I can do this.
I already did the connection:
'mysql' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'forge'),
'username' => env('DB_USERNAME', 'forge'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mysql2' => [
'driver' => 'mysql',
'url' => env('DATABASE_URL'),
'host' => env('DB_HOST_2', '127.0.0.1'),
'port' => env('DB_PORT_2', '3306'),
'database' => env('DB_DATABASE_2', 'forge'),
'username' => env('DB_USERNAME_2', 'forge'),
'password' => env('DB_PASSWORD_2', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => 'utf8mb4',
'collation' => 'utf8mb4_unicode_ci',
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
in my .env I have:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=example
DB_USERNAME=root
DB_PASSWORD=pass
DB_HOST_2=127.0.0.1
DB_PORT_2=3306
DB_DATABASE_2=example_hist
DB_USERNAME_2=root
DB_PASSWORD_2=pass
I already inserted the command in the kernel and this is the code I have now:
public function handle()
{
$users = DB::table('users')->where('state', 'Disabled')->get();
$user_hist = DB::connection('mysql2')->select('users');
//should be something here that copies the row from $users
}
Create one more field as copied which will be default false, and it will be true once its copied to other database
Run query whose state is disabled and not copied
$users = DB::table('users')->where('state', 'Disabled')
->where("copied", "=", 0)->get();
Run users loop
foreach ($users as $user){
//Now using connection insert into another table of another db
DB::connection('mysql2')->insert('insert into users (name, email, mobile, password, created_at, state) values (?,?,?,?,?,?)', array($user->name , $user->email , $user->mobile, $user->password, $user->created_at, $user->state ) );
//Make user copied status to true so next time it wont copied again
$user->copied = true;
$user->save();
}
Well, with the help of #Teekay I could manage to find myself the right solution. This worked for me. Hope this can help anyone with the same problem.
public function handle()
{
$users = DB::table('users')->where('state', 'Disabled')->where("copied",'false')->get();
if($users){
foreach ($users as $user){
DB::connection('mysql2')->insert('insert into users (name, email, mobile, password, created_at, state) values (?,?,?,?,?,?)', array($user->name , $user->email , $user->mobile, $user->password, $user->created_at, $user->state ) );
DB::table('users')->where('state', 'Disabled')->where("copied", 'false')->update(['copied' => 'true']);
}
}
}

Wordpress filter post between dates

So I have created a category in wordpress where I post some events. I have created two custom field where I insert two dates ( duration of the event ). Now my client wants to have 3 sort options ( current, upcoming, past ) that should be present in a dropdown menu.
For that i have managed to create this:
if($_ISSET('sort') && $_GET['sort'] == 'upcoming') {
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'm77_datefrom',
'value' => date('Y-m-d'),
'compare' => '>'
),
),
);
}
else if($_ISSET('sort') && $_GET['sort'] == 'past'){
$args = array(
'post_type' => 'post',
'meta_query' => array(
array(
'key' => 'm77_datefrom',
'value' => date('Y-m-d'),
'compare' => '<'
),
),
);
}
The problem is that I cannot insert the "sort" parameter.
Url structure : domain.com/category/events
Any ideas how can i solve this problem ? Or is there a better way to do this ?

Cakephp 3.0 join in three table

I am trying to fetch the data from three table in cakephp 3.0
There is three table
1) size_category
2) sizes
3) sizerelations
Below is the file wise code
Model SizeCategoryTable.php
public function initialize(array $config)
{
parent::initialize($config);
$this->table('size_category');
$this->displayField('sizeCat_Id');
$this->primaryKey('sizeCat_Id');
// used to associate the table with user table (join)
$this->belongsTo('Users', [
'className' => 'Users',
'foreignKey' => 'CreatedBy',
'propertyName' => 'user'
]);
$this->hasMany(
'Sizerelations', [
'className' => 'Sizerelations',
'foreignKey' => 'Scat_Id',
'propertyName' => 'sizerelations'
]
);
}
Controller SizeCategoryController
public function index($id = null)
{
$customQuery = $this->SizeCategory->find('all', array(
'contain' => array(
'Users',
'Sizerelations' => array(
'Sizes' => array(
'fields' => array('id', 'Size_Code')
)
)
)
));
//debug();die();
$this->set('sizeCategory', $this->paginate($customQuery));
$this->set('_serialize', ['sizeCategory']);
}
I am greeting the error of Sizerelations is not associated with Sizes

Cakephp: group not working

Here is the Model that I've written:
public function getMockTestResultDetails($studentID){
$mockTestResults = array();
$mockTestResults = $this->find('all',array(
'joins' => array(
array(
'table' => 'exam',
'alias' => 'exm',
'type' => 'LEFT',
'conditions' => array('StudentExam.TEMPLATEEXAM=exm.ID' ),
)
),
'fields' => array('exm.ENTRANCEEXAM', 'exm.NAME','count(StudentExam.TEMPLATEEXAM)' ,'StudentExam.IMPROVEMENT_INDEX' ,`StudentExam.EXAM_COMPLETED_ON`,'StudentExam.PHASE_ONE',
'StudentExam.PHASE_TWO','StudentExam.PHASE_THREE','StudentExam.PHASE_FOUR','StudentExam.PHASE_INTERN'),
//'group' => array(`StudentExam.TEMPLATEEXAM`),
'conditions' => array('exm.EXAM_TYPE' => 'MOCK','StudentExam.STUDENT' => $studentID,'StudentExam.STATUS' => 'COMPLETED'),
));
return $mockTestResults;
}
When I comment the line where 'group' is it works and I get a output but it is partial/incomplete output. I must use group to obtain the right answer. The same query when executed on phpmyadmin it works fine but it is not working in cakephp. Am I missing something here or what please suggest me the solution.

How to parse complicated hash ref in perl?

I used JSON::Parse to decode a json file. When I dumped it to a file it looks as printed below. I need to extract the 'url' from each of the repositories. How can I go about doing that? I have tried to access the elements, but cannot seem to get to them. Any suggestions?
How I decoded the .json file:
my $json_hash_ref = {};
$json_hash_ref= json_file_to_perl ($REPO_JSON_FILE) or confess "No repos found";
This is the data dump:
$VAR1 = {
'repositories' => [
{
'size' => 2970,
'watchers' => 49,
'created_at' => '2012-03-20T05:04:42Z',
'url' => 'http://github.cerner.com/aeon-core/aeon-topology',
'open_issues' => 0,
'followers' => 49,
'owner' => 'aeon-core',
'has_downloads' => 1,
'has_issues' => 0,
'language' => 'Java',
'pushed' => '2014-06-17T18:32:37Z',
'private' => ${\$VAR1->{'repositories'}[0]{'has_issues'}},
'name' => 'aeon-topology',
'score' => '1',
'has_wiki' => ${\$VAR1->{'repositories'}[0]{'has_issues'}},
'pushed_at' => '2014-06-17T18:32:37Z',
'description' => '',
'username' => 'aeon-core',
'created' => '2012-03-20T05:04:42Z',
'homepage' => '',
'forks' => 59,
'fork' => ${\$VAR1->{'repositories'}[0]{'has_issues'}},
'type' => 'repo'
},
{
.....
},...
my #urls = map $_->{url}, #{ $json_hash_ref->{repositories} };
For good information on traversing deep data structures, read the perl references tutorial.