How do I edit a cart order by adding more items and updating existing data in mysql with codeigniter..? - codeigniter-3

This code gets the existing cart content, add more items and try to update the data or insert new data
if ($cart = $this->cart->contents()) {
foreach ($cart as $key => $value) {
$order_details = array(
'oid' => $id,
'p_id' => $value['id'],
'qty' => $value['qty'],
'price' => $value['price'],
'total_amnt' => $value['qty'] * $value['price'],
'created_at' => date('Y-m-d h:i:s')
);
$q = $this->db->where('oid',$id)->get('order_details')->num_rows(); // oid is a foreign Key inside order_details table
if ( $q > 0 ){
$this->db->where('oid',$id); // oid is a foreign Key inside order_details table
$this->db->update('order_details',$order_details);
} else {
$this->db->set('oid', $id); // oid is a foreign Key inside order_details table
$this->db->insert('order_details',$order_details);
}
}
}

I simple load the existing data into cart and clear update the data in the database when saving. Another method was to delete the existing data and save the new one as current data..

Related

Show name of the project in the table list of event

I want to show the "Project" Name. Under the project, I have created an event, and on the listing page, I want to show the name of the project not the id of the project.
Both tables share the relationship between them.
I am using a laravel-backpack.
1)The below is the event model.
public function eventProject()
{
return $this->belongsTo('App\Models\Project','project_id','id');
}
2) And the project model like this.
public function projectEvent()
{
return $this->hasMany('App\Models\Event', 'project_id', 'id');
}
how can I show in the grid list like this, 'Project name', 'Event name', etc?
I hope this will help.
You put a setColumnDetails into the setupListOperation in your crud controller.
$this->crud->setColumnDetails( 'project_id', [
'label' => "Project", // Table column heading
'type' => 'text',
'name' => 'project.project_name', // the column that contains the ID of that connected entity;
// 'entity' => 'project', // the method that defines the relationship in your Model
'attribute' => "project.name", // foreign key attribute that is shown to user
'model' => "App\Models\Project", // foreign key model,
'orderable' => true,
'orderLogic' => function ( $query, $column, $column_direction ) {
return $query->join( 'projects', 'projects.id', '=', 'events.project_id' )
->orderBy( 'project.id', 'desc' );
},
'searchLogic' => function ( $query, $column, $searchTerm ) {
$query->orWhereHas( 'project', function ( $q ) use ( $column, $searchTerm ) {
$q->where( 'projects.name', 'like', '%' . $searchTerm . '%' );
} );
}
] );
This basically just changes it from the id to the name field, assuming the project name is stored in the "name" field.

Doctrine Entity values are all null except for id

I'm trying to fetch an Object from the database with the repository method findOneBy (id).
Basically, the line looks like this:
public function findAssignedTickets(User $user)
{
$userId = $user->getId();
$ticketMapping = new ResultSetMapping;
$ticketMapping->addEntityResult(Ticket::class, 't');
$ticketMapping->addFieldResult('t', 'id', 'id');
// Postgresql Native query, select all tickets where participants array includes the userId
$query = "SELECT *
FROM (
SELECT id, array_agg(e::text::int) arr
FROM ticket, json_array_elements(participants) e
GROUP BY 1
) s
WHERE
$userId = ANY(arr);
";
$results = $this->getEntityManager()->createNativeQuery($query, $ticketMapping)->getResult();
$results = array_map(function($item) {
return $item->getId();
}, $results); // Transform to array in integers
dump($results); // array:2 [0 => 83, 1 => 84] -> It's correct
$tickets = [];
foreach ($results as $ticketId) {
dump($this->findOneById($ticketId));
// $ticket = $this->findOneById($ticketId);
// $tickets[] = [
// 'identifier' => $ticket->getIdentifier(),
// 'title' => $ticket->getTitle(),
// 'author' => $ticket->getAuthor()->getUsername(),
// 'status' => $ticket->getStatus(),
// 'created' => $ticket->getCreatedAt()->format('c'),
// 'updated' => $ticket->getUpdatedAt()->format('c'),
// ]; // Ticket formatting to send in json
}
return $tickets;
}
which will output :
And I'm sure that the received id matches a row in the database, and that the database contains data, and all fields belong directly to the entity, except for author which represents a ManyToOne and I heard about the lazy displaying of Doctrine, but it shouldn't happen on other fields.
Why can't I retrieve data from the Object even with getters, and why are all the values set to null Except for id ?
EDIT : I was wondering if that had a connexion to the ResultSetMapping I used to fetch the tickets IDs in a totally separate request earlier, and when I added a addFieldResult('t', 'title', 'title'); it did the work, but not on the other fields, another mystery.

Retrieve the user id who posts a single entry of Gravity Form

Suppose that I know the entry ID ($lead_id), how can I retrieve the user who creates that entry.
I try to
$lead = RGFormsModel::get_lead( $lead_id );
$form = GFFormsModel::get_form_meta( $lead['form_id'] );
$values= array();
foreach( $form['fields'] as $field ) {
$values[$field['id']] = array(
'id' => $field['id'],
'label' => $field['label'],
'value' => $lead[ $field['id'] ],
);
}
But the user data is not there. I check sql database, and the user data is in wp_rg_lead table, not in wp_rg_lead_detail table.
Can anybody please help?
The information in the *_rg_lead table is accessible in the array that's returned by the get_lead function. So
user_id = $lead['created_by']
Also note that it's better to use the Gravity Forms API for retrieving the entry, specifically the get_entry function:
GFAPI::get_entry( $entry_id )
which will return an Entry object.

Column already exists in LeftJoin with Zend

With relationship and joins I'm trying get the latest post of each customer.
But I don't really get it to work. I get error:
Column already exists: 1060 Duplicate column name 'custID'
Based on my searching both here and Google it could have been for * but I have removed so all table columns is specified by name so I don't get why I get column already exists?
$db = $this->getDbTable();
// create sub query
$subSql = $db->select()
->setIntegrityCheck(false)
->from(array('s1' => 'sales'), array('s1.custID', 's1.saledate'))
->joinLeft(array('s2' => 'sales'), 's1.custID = s2.custID AND s1.saledate < s2.saledate', array('s2.custID', 's2.saledate'))
->where('s2.custID IS NULL')
->limit(1);
//main query
$sql = $db->select()
->setIntegrityCheck(false)
->from(array('customers' => 'customers'), array("customers.custID"))
->joinLeft(array('sale_tmp' => new Zend_Db_Expr('(' . $subSql . ')')), "customers.custID = sale_tmp.custID", array('sale_tmp.custID'));
//echo $sql->assemble();
//exit;
$resultSet = $db->fetchAll($sql);
return $resultSet;
Since two of your tables have the field custID, there is a conflict about how to populate the custID value in your joined table.
You need to provide a column-alias for one of them. The signature of the joinLeft() method is:
joinLeft($table, $condition, [$columns])
The third argument $columns can be a straight integer-indexed array of columns (as you are using) or it can be an associative array whose values are the columns, but whose keys are the column-aliases.
So perhaps try something like:
// create sub query
// add alias for the custID field
$subSql = $db->select()
->setIntegrityCheck(false)
->from(array('s1' => 'sales'), array('s1.custID', 's1.saledate'))
->joinLeft(array('s2' => 'sales'), 's1.custID = s2.custID AND s1.saledate < s2.saledate', array('sales_custID' => 's2.custID', 's2.saledate'))
->where('s2.custID IS NULL')
->limit(1);
// main query
// add alias for custID field
$sql = $db->select()
->setIntegrityCheck(false)
->from(array('customers' => 'customers'), array("customers.custID"))
->joinLeft(array('sale_tmp' => new Zend_Db_Expr('(' . $subSql . ')')), "customers.custID = sale_tmp.custID", array('temp_custID' => sale_tmp.custID'));

zf1: chained joins

I'm getting an error with a query, my question is: can i chain joins?
My first join is to the primary table, but my second join is to the table joined to the primary table. This is the query:
$query = $this->getDbTable()->select()
->from(array('ca' => 'contracts_allotment'),
array('id',
'contracts_rooms_id' => new Zend_Db_Expr("CONCAT(room_type_desc, '-', room_characteristics_desc)")
))
->join(array('cr' => 'contracts_rooms'),
'ca.contract_rooms_id = cr.id',
array())
->join(array('rt' => 'room_types'),
'cr.room_id = rt.id',
array('room_type_desc'))
->join(array('rc' => 'room_characteristics'),
'cr.char_id = rc.id',
array('room_characteristics_desc'))
->where('contract_id = ?', $contractId);
var_dump($this->getDbTable()->fetchAll($query));die;
I'm getting:
Select query cannot join with another table"
The error comes from Zend/Db/Table/Select::assemble()
Here you have some inside assemble():
// Check each column to ensure it only references the primary table
if ($column) {
if (!isset($from[$table]) || $from[$table]['tableName'] != $primary) {
var_dump($from[$table]['tableName'], $primary);die;
require_once 'Zend/Db/Table/Select/Exception.php';
throw new Zend_Db_Table_Select_Exception('Select query cannot join with another table');
}
}
The var_dump() prints:
string(10) "room_types" string(19) "contracts_allotment"
Any idea?
Don't forget to lock the tables when doing joins:
$query = $this->getDbTable()->select()
->setIntegrityCheck(false)
->from(array('ca' => 'contracts_allotment'),
array('id',
'contracts_rooms_id' => new Zend_Db_Expr("CONCAT(room_type_desc, '-', room_characteristics_desc)")
))
->join(array('cr' => 'contracts_rooms'),
'ca.contract_rooms_id = cr.id',
array())
->join(array('rt' => 'room_types'),
'cr.room_id = rt.id',
array('room_type_desc'))
->join(array('rc' => 'room_characteristics'),
'cr.char_id = rc.id',
array('room_characteristics_desc'))
->where('contract_id = ?', $contractId);
->setIntegrityCheck(false) should at least get you a new error.