Conditional Update Record Codeigniter - php

I would like to ask if its possible to put a Conditional for the UPDATE. First of all I have two tables.
billing_records:
brecord_id (PK)
date_billed
monthly_rent
water
electricity
total_payable
status (paid/unpaid)
payment_records
payment_id (PK)
date
type_payment (cash/cheque/on_bank)
amount_payable
change
balance
cheque_number
bank_number
brecord_id (FK)
I would like the code to go like this during insertion records on database:
IF balance==0
UPDATE status to 'paid' from billing_records TABLE
else
UPDATE total_payable(of billing_records) = balance(of payment_records)
During submit button I have two actions to make, to insert data in payment_records and UPDATE billing_records. I don't have problems inserting data in payment records, only updating the billing_records.
I'm having trouble in this line on my Controller
// 4. call model to save input to database table
$this->m_account_statement->insertPayableRecords($data);
$this->m_account_statement->changeStatusToPaid($brecord_id);
Here is my code:
Controller:
public function managePayment($brecord_id=0){
if($this->_submit_validate_payment($this->input->post('type_payment'))===FALSE){
$row = $this->m_account_statement->payableRecord($brecord_id);
$data['amountPayable'] = $row->result();
$data['brecord_id'] = $brecord_id;
return $this->load->view('admin/vrecord_payment',$data);
} else {
// 2. get the inputs
$data['payment_id'] = $this->input->post('payment_id');
$data['amount_payable'] = $this->input->post('amount_payable');
$data['amount_received'] = $this->input->post('amount_received');
$data['type_payment'] = $this->input->post('type_payment');
$data['cheque_number'] = $this->input->post('cheque_number');
$data['bank_number'] = $this->input->post('bank_number');
$data['balance'] = $this->input->post('balance');
$data['change'] = $this->input->post('change');
$data['brecord_id'] = $this->input->post('brecord_id');
$data['date'] = $this->input->post('date_transaction');
// 4. call model to save input to database table
$this->m_account_statement->insertPayableRecords($data);
$this->m_account_statement->changeStatusToPaid($brecord_id);
// 5. confirmation of registration
$this->session->set_flashdata('message',' Successfully Record Payment');
redirect('caccount_statement/displayTenants');
}
}
Model:
public function changeStatusToPaid($billing_id)
{
$this->db->query("UPDATE billing_record SET status = 'paid' WHERE brecord_id = $billing_id");
}
public function insertPayableRecords ($data){
if($this->db->insert('payment_record', $data)){
return TRUE;
}
return FALSE;
}

It is possible to put a condition you can use this flow.
if balance==0
//then fetch a record for status
//means run a query to get status
//now update
else
// select some different values for update
// now update query with fetched values

public function managePayment($brecord_id=0){
//check if id is present or not like this:
if ($brecord_id > 0) {//Update
// ... put your update code ...
} else { //Add
// ... put your add code ...
}
}

Related

Trying to change what column this code checks

Simple question. What does this code do?
public function claim(Request $request){
$comment = Comment::where('key',$request->key)->where('is_deleted','No')->first();
if(!empty($comment)){
return 1;
}else{
return 0;
}
}
I've tried changing what keys it's trying to match, but then it breaks.
EDIT:
Based on the answers I've got so far, it sounds like its checking for comments who's key matches the requested one. When I change the code to this, the form stops responding:
public function claim(Request $request){
$user = User::where('key',$request->key)->where('is_deleted','No')->first();
if(!empty($user)){
return 1;
}else{
return 0;
}
}
EDIT 2:
I have a table called Posts and a table called Users. Each entry on the Post table has a unique ID, a Title, and a Key (B_Key). That Key matches only 1 entry in the Users table. Each User has 3 keys (A_Key, B_Key, C_Key).
I'm trying to make my form ask for A_Key, then check if the User with that A_Key also has the B_Key that was used to publish this specific post. I tried writing a SQL query but have failed. Here is is:
$post = "SELECT posts.id, users.A_Key FROM posts INNER JOIN posts ON posts.id=users.A_Key WHERE posts.is_deleted = No";
if(!empty($post)){
return 1;
}
else{
return 0;
}
}
If there is any comment which is related with key and if didn't has then result will return 1 (true) else 0 (false)

How to fetch a record having max column value in phalcon?

I am trying to fetch a row/record having max faq_order column.
Scenario: I have a table faq_category and it contains a field faq_order. FAQ_ORDER column is responsible for storing the order number.
While creating new record in faq_category I want to set faq_order but it should be having latest value. i.e let say if there is 2 previous records so that records will be having faq_order values 1, 2 respectively! Now on third new record it should set the faq_order to 3 but I tried the below code but didn't found a proper way.
Save function:
public function saveGeneralFaqCategoryAction(){
// Instantiate new form for EbFaqCategoryModel
$form = new EbFaqCategoryForm();
if( $form ->isValid($this->request->getPost())){
// Get the FAQ Category id (if any)
$id = $this->request->get( 'id', null );
// Get existing FAQ Category (if any) or create a new one
if( null !== $id && $id !== '' ) {
$faqCategory = EbFaqCategoryModel::findFirst( $id );
} else {
// Here we create new instance and I'm stuck here!
// Logic in my mind is get max order and +1 it and then save it
// in new instance
$faqCategory = new EbFaqCategoryModel();
//$maxOrder = EbFaqCategoryModel::get();
$faqCategory->setFaqOrder(); // On new I want to set max value
}
// Bind form with post data
$form->bind( $this->request->getPost(), $faqCategory );
$faqCategory->save();
} else {
// Send error Json response
return CxHelper::SendJsonError($form->getHtmlFormattedErrors());
}
// Return success
return array( 'data' => 'Success' );
}
Model:
/**
* Get Current Max Order
*
* #return array
*/
public static function getCurrentMaxOrder(){
$queryBuilder = new Builder();
return $queryBuilder
->from(array('c' => static::class))
->columns('c.*')
->where('c.faq_order', MAX) // HERE I want to get a Record having faq_order max
->orderBy("c.date_created desc")
->getQuery()
->execute()->setHydrateMode(Resultset::HYDRATE_ARRAYS)
->toArray();
}
You should be using ORM aggregation functions: https://docs.phalconphp.com/3.2/en/db-models#generating-calculations
Here is one way of doing it:
function beforeValidationOnCreate()
{
$this->faq_order = \YourModelClassame::maximum([
'column' => 'faq_order'
]) + 1;
}
This way when you are creating record from this table it will always have the highest faq_order value :)

Move data from one table with button to another table Laravel

I have found this:
Move data from one MySQL table to another
But in Laravel it's a bit different. Like him I want a button which deletes a row in a table like this one:
(Updated picture)
Just to have an example. After he hit the button it should move the shown row into the database just like it is shown here and delete it afterwards. I really don't know how to start something like this in Laravel and I really can't find something related.
Maybe this will make it more clear:
$user_input = $request->userInput
$scores = DB::table('cd')
->join('customers', 'cd.fk_lend_id', '=', 'customer .lend_id')
->select('cd.fk_lend_id','cd.serialnumber','users.name', 'cd.created_at as lend on')
->where('cd.fk_lend_id',$request->$user_input)
->get();
Suppose you have two tables: firsts and seconds
For Laravel you must have two Models for these two tables: First and Second respectively.
Now, in your controller,
//import your models
use App\First;
use App\Second;
//create a function which takes the id of the first table as a parameter
public function test($id)
{
$first = First::where('id', $id)->first(); //this will select the row with the given id
//now save the data in the variables;
$sn = $first->serialnumber;
$cust = $first->customer;
$lendon = $first->lend_on;
$first->delete();
$second = new Second();
$second->serialnumber = $sn;
$second->customer = $cust;
$second->lend_on = $lendon;
$second->save();
//then return to your view or whatever you want to do
return view('someview);
}
Remember the above controller function is called on button clicked and an id must be passed.
The route will be something like this:
Route::get('/{id}', [
'as' => 'test',
'uses' => 'YourController#test',
]);
And, your button link like:
Button
This might be a simpler way to do the Laravel "move record" part of this.
use App\Http\Controllers\Controller;
use App\Models\TableOne;
use App\Models\TableTwo;
use Illuminate\Http\Request;
class MoveOneRecord extends Controller
{
public static function move_one_record(Request $request)
{
// before code
// get id
$id = intval( $request->input('id', 0) );
// grab the first row of data
$row_object = TableOne::where('id', $id))->first();
// check if we have data
if (empty($row_object)) { throw new Exception("No valid row data."); }
// convert to array
$row_array = $row_object->toArray();
// unset the row id (assuming id autoincrements)
unset($row_array['id']);
// insert the row data into the new table (assuming all fields are the same)
TableTwo::insert($row_array);
// after code
}
}

codeigniter dynamic field added on migration time

i have two database called "migrate_new" and "migrate_old" and both have one table called "cms_pages".
i want to compare "migrate_old" db "cms_pages" with the "migrate_new" "cms_pages" table structure if "migrate_new" database "cms_pages" does not have "field" then alter table automatically.
below is my code to compare "migrate_old" "cms_pages" fields not in
"migrate_new" "cms_pages" now i want to add this fields on table.
i want to continue the process in place of exit.
**> any one can have idea to add fields automatically so no need to stop
migration task?
i am not able to get field details like type , key , etc.
how i know alter table with use modify or add fields.
i short i want to set structure with out loss of any data automatically.
thanks in advance..
**
$this->load->database();
$admin_db = $this->load->database('ADMINDB', TRUE);
$query = $this->db->get('cms_page');
$result = $query->result();
$fields_old = $this->db->list_fields('cms_page');
// $fields_new = $admin_db->list_fields('cms_page');
$flag = false;
foreach ($fields_old as $field){
if (!$admin_db->field_exists($field, 'cms_page'))
{
echo $field.'=> is not exists in new table please contact to developer for that <br>';
$flag = true;
}
}
if($flag){
exit;
}

Yii composite primary keys with isNewRecord

I have a mysql table with composite keys ( user_id , category_id );
I am trying to update the last access for these records as following
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
echo $userCategory->isNewRecord; //always true
$userCategory->last_access = Now();
$userCategory->save();
The {$userCategory->isNewRecord} and when I try to save() the MySQL generates a duplicate error for the composite Primary keys.
I also added this to UserCategory model but didn't help
public function primaryKey() {
return array('user_id', 'category_id');
}
****Update:
Sorry for the confusion. My question is how to achieve the same result as "ON DUPLICATE KEY UPDATE" in the Yii framework. In other words, how to do the insert or update in one SQL query. if you look at the source code for save()
public function save($runValidation=true,$attributes=null)
{
if(!$runValidation || $this->validate($attributes))
//checking if new record
return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);**
else
return false;
}
Actually, the problem is that if isNewRecord is always true, it means that Yii is going to use an INSERT statement instead of an UPDATE statement when saving the model to the database.. that is why you always get the duplicate pk error, even if it's composite.
Here is the official documentation about IsNewRecord . So, the problem is that you're using
$userCategory = new UserCategory; //Always a new record, tries to INSERT
So to resolve this you have to find the record and evaluate if it is found before saving it, instead. Documentation can also be read Here about the find() family of methods and their return value, the return values of the find() methods vary slightly on their nature:
find..() returns the record found or NULL if no record is found.
findAll..() returns an array containing all the records found or an empty array if no records are found.
You can use this return value to differentiate wether a primary key exists or not:
$userCategory = UserCategory::model()->findByAttributes(array('user_id '=>1,'category_id '=>15));
// if user does not exist, you need to create it
if ($userCategory == NULL) {
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
}
echo $userCategory->isNewRecord; //you will see the difference if it does exist or not exist
$userCategory->last_access = Now();
$userCategory->save();
This will ensure that the framework uses the INSERT or UPDATE statement correctly, avoiding the duplicate PK error you're getting.
Edit: Enhanced the example code to properly populate the record when it's new.
In your model, add the following method:
/**
* Uses the primary keys set on a new record to either create or update
* a record with those keys to have the last_access value set to the same value
* as the current unsaved model.
*
* Returns the model with the updated last_access. Success can be checked by
* examining the isNewRecord property.
*
* IMPORTANT: This method does not modify the existing model.
**/
public function updateRecord(){
$model = self::model()->findByPk(array('user_id'=>$this->user_id,'category_id'=>$this->category_id));
//model is new, so create a copy with the keys set
if(null === $model){
//we don't use clone $this as it can leave off behaviors and events
$model = new self;
$model->user_id = $this->user_id;
$model->category_id = $this->category_id;
}
//At this point we have a model ready for saving,
//and don't care if it is new or not
$model->last_access = $this->last_access;
$model->save(false);
return $model;
}
The above is inspired by a more general method that I use a lot to do a create-or-find-if-already-exists process.
Use the following code to execute this.
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
echo $userCategory->isNewRecord; //always true
$userCategory->last_access = Now();
$userCategory = $userCategory->updateRecord();
Note that only the last line is different from your code. The fact that the instance of the model declared with new UserCategory is not altered is intended behavior.
You can then verify in your code whether or not the model saved with the following:
if(!$userCategory->isNewRecord){
echo 'save succeeded';
}
else{
echo 'save failed';
}
If you're trying to update, you should load record, instead of creating a new one.
UserCategory::model()->findByPk(array('user_id'=> 1,'category_id '=> 15));
$userCategory->last_access = Now();
$userCategory->save();
in UserCategory.php
public function isNewRecord()
{
$result = $this->findByAttributes(array('user_id'=>$this->user_id,'category_id'=>$this->category_id));
if($result === NULL)
{
return true;
}
return false;
}
then in the controller
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
echo $userCategory->isNewRecord();
----
Another option is to modify the model to change the condition on the save function then call the parent save function: (this code goes in the UserCategory model)
public function save($runValidation=true,$attributes=null) {
$exists = UserCategory::model()->findByAttributes(array('category_id'=>$this->category_id,'user_id'=>$this->user_id));
if($exists) {
$this->isNewRecord = false;
}
return parent::save($runValidation,$attributes);
}
I just did a test and it seems to work correctly. You should just be able to do this:
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
$userCategory->last_access = Now();
$userCategory->save();
Should insert or update based off of whether it finds the record, so you don't have to change any of your other code.

Categories