Phalcon MySQL UPDATE not working - php

I am trying to create RESTful API and I am trying to update my MySQL database row through Phalcon via pure queries. But I run into the issue that the query is runned Phalcon status->success() returns true but when I look into the db values are the same as before.
I tried to change from SQL queries to using model->update() but has the same issue. Both values country_id and university_id are integers.
Any clue or workaround?
My POST handling function:
$app->post("/api/user/university/{id:[0-9]+}", function($id) use ($app){
$university_id = $app->request->getPost("university_id");
$country_id = universities::findFirstById($university_id)->country_id;
$phpql = "UPDATE users
SET university_id=:university_id:,
country_id=:country_id:
WHERE
id=:user_id:";
$status = $app->modelsManager->executeQuery($phpql, array(
'user_id' => $id,
'university_id' => $university_id,
'country_id' => $country_id
));
$response = new Response();
if($status->success() == true){
$response->setStatusCode(201, "Created");
$response->setJsonContent(
array(
'status' => 0
)
);
} else {
$response->setStatusCode(409, "Conflict");
$errors = array();
foreach ($status->getMessages() as $message) {
$errors[] = $message->getMessage();
}
$response->setJsonContent(
array(
'status' => 'ERROR',
'messages' => $errors
)
);
}
return $response;
});

Is university_id and country_id part of PK ? If yes then phalcon don't allow to change primiary keys. If you need such behaviour remove those columns from primiary key and use uniquness validator.

Related

Unable to save select box options in Laravel 5.1

I am working on my first project using Laravel 5.1. Uses a selectbox in a form.
{!!Form::select('animal_parent[]', array('1' => 'opt1', '2' => 'opt2', '3' => 'opt3', '4' => 'opt4',), null, ['id' => 'animal_parent', 'disabled' => 'disabled', 'multiple' => 'multiple', 'class' => 'form-control'])!!}
Selection limited to two options which need to saved in two columns, male_parent and female_ parent of the animal table.
There are no male_parent and female_ parent element names in the form. Similarly no animal_parent field in animal table.
Values are set as expected in the code given below. However, the insert command does not reflect the newly set values and throws an error.
"ErrorException in helpers.php line 671: preg_replace(): Parameter mismatch, pattern is a string while replacement is an array."
Any help would be much appreciated.
First attempt using mutators
public function setMaleParentAttribute()
{
$parent = Input::get('animal_parent');
$this->attributes['male_parent'] = intval($parent[0]);
}
public function setFemaleParentAttribute(AddAnimalRequest $request)
{
$parent = Input::get('animal_parent);
if (isset($parent[1])) {
$this->attributes['female_parent'] = intval($parent[1]);
} else {
$this->attributes['female_parent'] = intval($parent[0]);
}
unset($request->animal_parent);
}
Second attempt using the store() method in the controller.
$animal = new Animal($request->all());
$parent = Input::get('animal_parent');
$animal['male_parent'] = intval($parent[0]);
if (isset($parent[1])) {
$animal['female_parent'] = intval($parent[1]);
} else {
$animal['female_parent'] = intval($parent[0]);
}
unset($request->animal_parent);
Auth::user()->animals()->save($animal);
return redirect('animals');
The problem was then solved with a change in UI. I feel the problem could have been solved using the below method. Hope that helps someone.
$input = $request->all();
$parent = $input['animal_parent'];
$input['male_parent'] = intval($parent[0]);
if (isset($parent[1])) {
$input['female_parent'] = intval($parent[1]);
} else {
$input['female_parent'] = intval($parent[0]);
}
unset($input['animal_parent']);
$animal = new Animal($input);
$animal->save();`

Yii2-mongodb: How can i write update query in yii2 specific to php mongodb?

I am recently studing yii2. I am using mongodb at backend database. I am confused for the update query i found in the documentation
public function actionUpdate($id)
{
$query = new Query;
$row = $query->from('item')
where(['_id' => $id]) // implicit typecast to [[\MongoId]]
->one();
...
}
I am writing php specific mongodb query as follows...
$update = array('$set' => array("status" => 'read', "agencyStatus" => 'unread'));
$where = array("_id" => new MongoId($id));
$mongoDb->update($where, $update);
how the syntax would be in yii2 specific mongodb???
You can generate Mongo model using gii(video) and do in your controller something like:
$item = Item::find()->where(["_id" => new MongoId($id)]);
$item->status = 'read';
$item->agencyStatus= 'unread';
$item->save();

Saving data after read

I'm trying to save data after the same model read it. Here's my code:
public function partner($postid, $partner){
$this->Partner->id = $postid;
$this->Partner->id = $partner;
$this->Partner->ip = $_SERVER['REMOTE_ADDR'];
$result = $this->Partner->read();
if($result){
$time = $result['Partner']['time'];
pr($result);
}
$data = array('id' => $partner,
'post' => $postid,
'time' => time(),
'cash' => '0.001',
'ip' => $_SERVER['REMOTE_ADDR']);
$this->Partner->save($data);
}
It just updates the data, but doesn't save it as a new row
Before $this->Partner->save($data);, call $this->Parter->create();, that will set the Partner model to save a new row.
EDIT: Unless id is your model's primary key and you're setting it to a value that already exists in the database, in that case it will update regardless of whether you use $model->create() or not. (I think).

CakePHP get matches in an array() based on hasMany relationship

PlanDetails hasMany Companies. PlanDetail table has company_id field.
This is all I need to achieve: PlanDetail.company_id = Company.id. So get all Plan Details where PlanDetail.company_id matches Company.id.
Here is the query I have been messing with in the plan_details_controller:
function pd_list_by_company() {
$this->PlanDetail->unbindModel(array('hasMany' => array('Plan')));
$comp_id = $this->PlanDetail->Company->find('all');
$result = $this->PlanDetails->find('all', array('conditions' => array
('Company.id' => 'PlanDetail.company_id')));
$company_id = $this->PlanDetail->read('company_id');
}
I cannot just get the results I need.. what am I doing wrong here?
Sounds like a simple condition on the company_id field to me:
$this->PlanDetail->find('all', array('conditions' => array('company_id' => $company_id)))
Or, if you want the company as well and your associations are hooked up correctly:
$company = $this->Company->read(null, $company_id);
// echo $company['Company']
// echo $company['PlanDetail'][0], $company['PlanDetail'][1] etc...
You need to get a $company_id to query on from somewhere, which is usually the URL:
public function pd_list_by_company($company_id)
Then visit this action with the URL /plan_details/pd_list_by_company/42, which can be linked to using $this->Html->link('foobar', array('controller' => 'plan_details', 'action' => 'pd_list_by_company', 42)).
Complete example:
public function view($planId) {
$plan = $this->PlanDetail->read(null, $planId);
if (!$plan) {
$this->cakeError('error404');
}
$otherPlansBySameCompany = $this->PlanDetail->find('all', array(
'conditions' => array('company_id' => $plan['PlanDetail']['company_id'])
));
$this->set(compact('plan', 'otherPlansBySameCompany'));
}
I am displaying the set() find result in the Plan Detail view.ctp.
This is how I solved it:
function view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid plan detail', true));
$this->redirect(array('action' => 'index'));
}
$this->set('planDetail', $this->PlanDetail->read(null, $id));
$cid = $this->PlanDetail->read('Company.id');
$cid_extract = Set::extract($cid, 'Company.id');
$this->set('planComps', $this->PlanDetail->find('all',array('conditions' => array("company_id" => $cid_extract))));
}

Passing models in array format to views in YII

How can I pass the model in array format.
I want to pass models in this format from controller to view:-
Users[user_contact]=Contact
Users[user_contact][contat_city]=City
Users[user_contact][contact_state]=state
This is what I am doing
public function actionCreate() {
$user = new Users;
$presContact = new Contacts;
$presCity = new Cities;
$presState = new States;
$contactArr = array();
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if (isset($_POST['Users'])) {
$transaction = CActiveRecord::getDBConnection()->beginTransaction();
$contactArr = CommonFunctions::saveContact($_POST['Users']['user_pres_contact'],'user_pres_contact',$errorArr);
$presContact = $contactArr['contact'];
$presCity = $contactArr['city'];
$presState = $contactArr['state'];
$user->attributes = $_POST['Users'];
$user->user_pres_contact_id = $presContact->contact_id;
if($user->save()){
$transaction->commit();
$this->redirect(array('view', 'id' => $user->user_id));
} else {
$transaction->rollback();
}
}
$this->render('createUser', array(
'Users' => $user,
'Users[\'user_pres_contact\']'=>$presContact,
'Users[\'user_pres_contact\'][\'contact_city\']'=>$presCity,
'Users[\'user_pres_contact\'][\'contact_state\']'=>$presState,
));
}
I am able to access only $users but
I m not able to access $Users['user_pres_contact'] in the view
That's because you are assigning them as strings...
The correct way of doing things would be (btw, what you are asking for can't done literally, it is impossible to assign 2 values to one key):
$user = array(
'user_press_contact' => array(
'contact' => $presContact,
'city' => $presCity,
'state' => $presState,
),
);
$this->render('createUser', array(
'Users' => $user,
));
It will give you $Users['user_press_contact']['contact'] for the name in the view, etc.
You can use
$user->getAttributes() //it returns an array of data.
Hope that's usefull
It is possible to solve this using model relations? You can define a relation from the User model to the City model (e.g. naming it relation_to_city), then you can just assign the user model in the controller
$this->render('view', 'user'=>$user);
and access the city (from the view)
$user->relation_to_city

Categories