Phalcon ORM Batch Update - php

Simple Questions, if you Phalcon users .. you know what i want trying to do.
$trueFind = ProductOrderTransaction::find(["conditions"=>"protPthdId = ".$id]);
$trueFind->setTransaction($transaction);
$trueFind->protMomsId = $monitId;
$trueFind->protMomsName = $monitName;
if (!$trueFind->update()) {
foreach ($trueFind->getMessages() as $message) {
$this->flash->error($message);
$transaction->rollback($message->getMessage());
}
}
I just want to do this query in orm Phalcon :
UPDATE product_order_transaction set protMomsId = '$monitId' , protMomsName = '$monitName' WHERE protPthdId='$id'
fail -> rollback.. success -> commit.

Something like this?
$items = ProductOrderTransaction::find([
'conditions' => 'protPthdId = :id:',
'bind' => ['id' => $id]
]);
foreach($items as $item){
$this->db->begin();
$item->protMomsId = $monitId;
$item->protMomsName = $monitName;
$update = $item->update();
if(!$update){
$this->db->rollback();
continue;
}
$this->db->commit();
}

Related

Shorter way in php laravel to load a model in another similar one?

I want to copy every property of the contract model into this another templatecontract model and so on. My code works, but I don't know much about laravel (or php in fact) and my intuition tells me that there must be a better way, or more elegant way.
fill() from Laravel does not get much better. Maybe with a constructor?
Equal tables:
Contract -> TemplateContract
Chapter -> TemplateChapter
Clause -> TemplateClause
public function storeTemplate(ContractCreateRequest $request)
{
DB::beginTransaction();
try
{
$contract = Contract::find($request->input()['type']);
$templatecontract = new TemplateContract();
$templatecontract->id = $contract->id;
$templatecontract->pid = $contract->pid;
$templatecontract->deleted = $contract->deleted;
$templatecontract->sorting = $contract->sorting;
$templatecontract->created_at = $contract->created_at;
$templatecontract->updated_at = $contract->updated_at;
$templatecontract->deleted_at = $contract->deleted_at;
$templatecontract->title = $contract->title;
$templatecontract->description = $contract->description;
$templatecontract->hidden = $contract->hidden;
$templatecontract->contract_type = $contract->contract_type;
$templatecontract->process_type = $contract->process_type;
$templatecontract->tstamp = $contract->tstamp;
$templatecontract->is_english = $contract->is_english;
$templatecontract->usecasetitle = $contract->usecasetitle;
if (Auth::user()) {
$templatecontract->user_id = Auth::user()->id;
}
if($templatecontract->save())
{
$chapter = DB::table('chapter')->where('contract', $templatecontract->id)->get();
if(isset($chapter))
{
foreach ($chapter as $key => $value) {
$templatechapter = new TemplateChapter();
$templatechapter->clause = $value->clause;
$templatechapter->contract = $value->contract;
$templatechapter->created_at = $value->created_at;
$templatechapter->deleted = $value->deleted;
$templatechapter->headlinetype = $value->headlinetype;
$templatechapter->hidden = $value->hidden;
$templatechapter->id = $value->id;
$templatechapter->must = $value->must;
$templatechapter->note = $value->note;
$templatechapter->sorting = $value->sorting;
$templatechapter->title = $value->title;
$templatechapter->tstamp = $value->tstamp;
$templatechapter->updated_at = $value->updated_at;
$templatechapters[] = $templatechapter;
if($templatechapter->save())
{
$clause = DB::table('clause')->where('chapter', $value->id)->get();
if(isset($clause))
{
foreach ($clause as $key => $value) {
$templateclause = new TemplateClause();
$templateclause->id = $value->id;
$templateclause->chapter = $value->chapter;
$templateclause->clausetext = $value->clausetext;
$templateclause->variable = $value->variable;
$templateclause->topic = $value->topic;
$templateclause->deleted = $value->deleted;
$templateclause->selectword = $value->selectword;
$templateclause->shortinfo = $value->shortinfo;
$templateclause->sorting = $value->sorting;
$templateclause->created_at = $value->created_at;
$templateclause->updated_at = $value->updated_at;
$templateclause->hidden = $value->hidden;
$templateclause->tstamp = $value->tstamp;
$templateclause->save();
$templateclauses[] = $templateclause;
}
}
}
}
}
}
//DB::commit();
return response()->success(__('success.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), $templatecontract, 200);
}
catch (Exception $e)
{
return response()->error(__('error.showing', ['resource' => 'des Vertrags', 'resourceE' => 'contract']), 400, $e);
}
}
So almost all of the props from the request matches with the column names. You just need to call the create method of Eloquent model to create a new record and pass key value pair but rather an object. Also, you need not to worry about the extra parameters $contract contains since Laravel will only extract and assign params defined in protected $fillable property of the class.
// cast object to array
$contract = (array) $contract;
$templateContract = TemplateContract::create($contract)

Laravel Error: Only variable references should be returned by reference

I am working on a web app with php laravel framework. I'm also using framwork eloquent.
When i create a new "user" and i send it to my database the error with
$myValue->save();
This is the error:
"at HandleExceptions->handleError(8, 'Only variable references should be returned by reference',
'C:\\wamp64\\www\\project\\Fiq-spsslsj\\app\\Http\\Controllers\\DossierController.php', 97, array('request' => object(Request), 'employe' => object(employe)))
in DossierController.php line 97"
I've seen some similar problem but they are not quite really usefull (the problem in the other topics talk about code ingniter and common.php).
public function ajouter(Request $request){
$employe = new employe;
$employe->No_Employe = $request->input('No_Employe');
$employe->Nom = $request->input('Nom');
$employe->Prenom = $request->input('Prenom');
$employe->Email = $request->input('Email');
$employe->Adresse = $request->input('Adresse');
$employe->Date_Naissance = $request->input('Date_Naissance');
$employe->Titre_Emploi = $request->input('Titre_Emploi');
$employe->Telephone = $request->input('Telephone');
$employe->Annee_Embauche = $request->input('Annee_Embauche');
$employe->Present_Travail = $request->input('optTrav');
$employe->Sexe = $request->input('optSexe');
$employe->Fumeur = $request->input('optFum');
$employe->Langue = $request->input('Langue');
if (DB::table('liste_ville')->where('Nom_Ville','=',$request->input('Ville'))->get() != null)
{
$employe->Fk_Id_Ville = DB::table('liste_ville')->where('Nom_Ville','=',$request->input('Ville'))->value('Id_Ville');
}
else
{
$newVille = ucfirst($request->input('Ville'));
DB::table('liste_ville')->insertGetId(['Nom_Ville' => $newVille]);
$MoreVille = DB::table('liste_ville')->get();
foreach ($MoreVille as $key => $v)
{
if(strtolower($request->input('Ville')) === strtolower($v->Nom_Ville)){
$employe->Fk_Id_Ville = $v->Id_Ville;
break;
}
}
}
$employe->Code_Postal = $request->input('Code_Postal');
$employe->Actif = $request->input('optActif');
if (DB::table('provinces')->where('Nom_Province','=',$request->input('Province'))->get() != null) {
$employe->Fk_Id_Province =DB::table('provinces')->where('Nom_Province','=',$request->input('Province'))->value('Id_Province');
}
else
{
$newProv = ucfirst($request->input('Province'));
DB::table('provinces')->insertGetId(['Nom_Province' => $newProv]);
foreach ($provinces as $key => $p)
{
if(strtolower($request->input('Province')) === strtolower($p->Nom_Province)){
$employe->Fk_Id_Province = $p->Id_Province;
break;
}
}
}
$employe->save();
return redirect('/dossiers');
}
The code above is the code in my controller.
I hope you'll be able to help me.
Try this in your controller
return redirect()->to('/dossiers');

save all associated records at once

I am able to save associated records in cakephp3 but if you look at the code , the records are not saved all at once with 1 save call.
I did have a problem trying to save all the records at once. If you look at how its done you see the Guardian and Users table are save separately.
The code works and saves the records but saving all at once in 1 save call has been an issue as I got an error on the guardian table.
Guardians have a 1 to many relationship with students
Students and Users have a 1 to 1
Students to subjects and availabilityFotStudents both have a many to many
Code
public function add($gId=0) {
$this->loadModel("Guardians");
$this->loadModel('PaymentTypes');
$this->set("title","Add Student");
$guardians=null;
if ($gId>0){
$guardians =$this->Guardians->get($gId);
}
if ($this->request->is('post')) {
if ( $this->request->data['studenttype']==0){ //enquiry
$this->request->data['students']['address_billing'] = 0;
$this->request->data['students']['student_enq'] = 1;
}
else if ( $this->request->data['studenttype']==1){ //waitlist
$this->request->data['students']['address_billing'] = 1;
$this->request->data['students']['student_enq'] = 0;
}
else if ( $this->request->data['studenttype']==2){ //skip waitlist
$this->request->data['students']['address_billing'] = 4;
$this->request->data['students']['student_enq'] = 0;
}
if ( $this->request->data['students']['tutoring_typest_id']==1){
$this->request->data['students']['group_status']=0;
}
else if ( $this->request->data['students']['tutoring_typest_id']>1){
$this->request->data['students']['group_status']=1;
}
if ($this->request->data['students']['tutoring_typest_id']==3 ){//group only
$this->request->data['students']['address_billing'] = 4;
}
$data = $this->request->data;
// debug($data);
$uname= $this->request->data['Users']['username'];
if ($this->Students->Users->findByUsername($uname)->count()) {
$this->Flash->error(__('Username exists. Please, try again.'));
return $this->redirect(["action"=>"add",$gId]);
}
$userId=0;
$entity = $this->Students->Users->newEntity($this->request->data['Users'],['validate'=>false]);
$entity->role = "student";
$entity['role_id'] = 4;
$entity = $this->Students->Users->save($entity);
// debug( $entity);
$studentUserId = $entity->id;
if($guardians==null) {
$guardians = $this->Guardians->newEntity($this->request->data['guardians'], ['validate' => false]);
}
$guardianEntity = $this->Guardians->save($guardians);
$guardians = $this->Students->newEntity();
$studentData = $this->request->data['students'];
$studentData['subjects'] = $this->request->data['subjects'];
$studentData['availability_for_students'] = $this->request->data['availability_for_students'];
$studentEntity = $this->Students->patchEntity($guardians,$studentData,
[
"validate"=>false,
'associated' => [
"AvailabilityForStudents"=>["validate"=>false],
"Subjects"=>["validate"=>false]
]
]
);
$studentEntity->guardian_id = $guardianEntity->id;
$studentEntity->user_id = $studentUserId;
$studentEntity = $this->Students->save($studentEntity,
[
"validate"=>false,
'associated' => [
"AvailabilityForStudents"=>["validate"=>false],
"Subjects"=>["validate"=>false]
]
]
);
if ($studentEntity) {
$this->Flash->success(__('The student has been saved'));
return $this->redirect(["action"=>"index2"]);
} else {
$this->Flash->error(__('The student could not be saved. Please, try again.'),'flash_alert');
}
}//post
$subjects = $this->Students->Subjects->find('list', array( 'order' => array('Subjects.name' => 'asc') ));
$weekdays = $this->Students->weekDays;
$tutoringTypes = $this->Students->TutoringTypeStudents->find('list');
//$payments = $this->Student->paymentOptions;
$this->PaymentTypes->primaryKey("name");
$payments = $this->PaymentTypes->find( 'list', array(
'fields' => array('PaymentTypes.name','PaymentTypes.name')) );
$referrals = $this->Students->Referrals->find('list');
$tutorGender = $this->Students->Lessons->Tutors->tutorGender;
$this->set('guardians', $guardians);
$this->set(compact('referrals','subjects', 'tutoringTypes', 'weekdays','payments','tutorGender'));
}
you can use Tranactional data save. Where you can run multiple save method. if any save method failed then no data will be save. so it works like "1 save call" which you mentioned

Not able to update mongo document with following code

Im using following code to update a mongo document. But its not working when I use $inc in order to increment a counter. It works well if no inc is used.
$arrWhere = array('epa_id' => $objData->request->memo->epa_id);
$arrSet = array(
'pa_response'=>$objData,
'response_status'=>'N',
'modified_datetime'=> getServerTimeStamp(),
array('$inc'=>array('revision_id'=>1)),
);
$arrResult = $objPriorAuth->updatePA($arrWhere, $arrSet);
public function updatePA($arrWhere,$arrSet)
{
global $medDB;
$strCollection = EPA_MASTER;
$dbCollection = $medDB->$strCollection;
$arrReturn = array();
//dump($arrSet);
try
{
$dbCollection->update(
$arrWhere,
array('$set' =>$arrSet),
array('multiple' => true)
);
dump($medDB->lastError());
}
catch(MongoCursorException $mce)
{
$arrReturn['error'] = $mce->getMessage();
logError($mce->getMessage(),DB_ERROR_LOG_FILE_PATH);
}
return $arrReturn;
}
It's wrong syntax, you can't use inc inside set. Try out the following code:
Change options:
$arrSet = array(
'pa_response'=>$objData,
'response_status'=>'N',
'modified_datetime'=> getServerTimeStamp()
);
$arrInc = array('$inc'=>array('revision_id'=>1));
Change update query:
array('$set' => $arrSet, '$inc' => $arrInc);

How to insert data in symfony table?

I have made a symfony form and I used:
$conn->insert('Invoiceshasitems', array('Invoiceitemsid' => '$items'));
for data insertion but it not works ho i do insert data from symfony controller.
here is my code:
$itemscounter = $request->request->get('itemscounter');
if(isset($_SESSION['invoiceid'])) {
$invoiceid=$_SESSION['invoiceid'];
//echo $invoiceid;
//exit;
}
//$entity= new Invoiceshasitems();
if($request->isXmlHttpRequest()) {
if($itemscounter > 1){
for($i=1; $i<=$itemscounter; $i++){
if($i==1){
$items = $_POST['items'];
}else {
$items.$i = $_POST['items'.$i];
}
}
}else{
$items = $_POST['items'];
$conn->insert('Invoiceshasitems', array('Invoiceitemsid' => '$items'));
}
}
You can use native query in Doctrine, there is some docs here: http://docs.doctrine-project.org/en/latest/reference/native-sql.html
For your example the code is something like that:
$rsm = new ResultSetMapping();
$query = $this->_em->createNativeQuery('INSERT INTO Invoiceshasitems SET Invoiceitemsid = ?', $rsm);
$query->setParameter(1, $items);
$result = $query->getResult();

Categories