Get just inserted id - zend-framework

I have here many-to-many table, i need to get just inserted id - BlogId. lastInsertId() is NULL result. Any ideas?
$table = new Blog_Model_Blog_Table();
$relTable = new Blog_Model_Relation_Table();
$Object = $table->createRow();
$form = new Blog_Form_Blog_Add($Object);
if ($this->getRequest()->isPost() and $form->isValid($_POST)) {
Blog_Model_Blog_Manager::add($Object);
$blogId = $table->getAdapter()->lastInsertId();
foreach ($_POST['category_id'] as $value) {
$relTable->insert(array('id' => $blogId, 'category_id' => $value));
}
Blog_Model_Blog_Manager:
class Blog_Model_Blog_Manager
{
static function add(Blog_Model_Blog_Item &$Object)
{
$data = array(
'time_add' => time(),
'time_edit' => time(),
'url_keyword' => Ap_Filter_Translit::asURLSegment($Object->name)
);
$Object->setFromArray($data)
->save();
}

I make it with mySql function LAST_INSERT_ID():
$blogId = $table->fetchRow($table->select()->from($table)->columns('LAST_INSERT_ID() as idi'));

Related

How can I add cart items to user meta table using WooCommerce REST_API

I'm building a Flutter app linked with WooCommerce through REST-API, and I want to add cart items to wc_session data in order to be able to update cart data for a specific user.
I found the below code and used it, It gives me a 200 response, but no items in the cart.
What's the problem? Should I implement a specific webhook for this task, or the rest API will do?
Also, how can I add session data to meta tables directly from the code, as I am afraid to corrupt the database.
The code:
<?php
defined( 'ABSPATH' ) || exit;
class WC_REST_Webhooks_Controller extends WC_REST_Webhooks_V2_Controller {
protected $namespace = 'wc/v3';
protected function get_default_api_version() {
return 'wp_api_v3';
}
protected $rest_base = 'custom';
function woocommerce_add_to_cart($param) {
global $wpdb;
$user_id = $param['user_id'];
wp_set_current_user($user_id);
$objProduct = new WC_Session_Handler();
$wc_session_data = $objProduct->get_session($user_id);
$full_user_meta = get_user_meta($user_id, '_woocommerce_persistent_cart_1', true);
if( defined( 'WC_ABSPATH' ) ){
include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
include_once WC_ABSPATH . 'includes/wc-notice-functions.php';
include_once WC_ABSPATH . 'includes/wc-template-hooks.php';
}
if ( null === WC()-> session ) {
$session_class = apply_filters( 'woocommerce_session_handler', 'WC_Session_Handler' );
WC()->session = new $session_class();
WC()->session->init();
}
if ( null === WC()->customer ) {
WC()->customer = new WC_Customer( get_current_user_id(), true );
}
if ( null === WC()->cart ) {
WC()->cart = new WC_Cart();
// force refresh cart contents from the session here.
WC()->cart->get_cart();
}
// create a new cart object
$cartObj = WC()->cart;
// Add old cart data to newly created cart obect:
if ($full_user_meta['cart']) {
foreach($full_user_meta['cart'] as $single_user_meta) {
$cartObj->add_to_cart( $single_user_meta['product_id'], $single_user_meta['quantity'] );
}
}
//Add product and quantities coming in request to the new cart object
if ($param['products']) {
WC()->cart->empty_cart();
foreach($param['products'] as $prod) {
$cartObj->add_to_cart( $prod['product_id'], $prod['quantity']);
}
}
$updatedCart = [];
foreach( $cartObj->cart_contents as $key => $val ){
unset($val['data']);
$updatedCart[$key] = $val;
}
// if there is a current session cart, overwrite it with the new cart
if( $wc_session_data ){
$wc_session_data['cart'] = serialize($updatedCart);
$serializedObj = maybe_serialize($wc_session_data);
$table_name = 'wp_woocommerce_sessions';
// Update wp session table with cart data:
$sql = "UPDATE $table_name SET session_value= '".$serializedObj."' WHERE session_key = '".$user_id."'";
// Execute the query:
$rez = $wpdb->query($sql);
}
// Overwrite the persistent cart with new cart data
$full_user_meta['cart'] = $updatedCart;
$productsInCart = [];
foreach($cartObj->cart_contents as $cart_item) {
$product = wc_get_product( $cart_item['product_id'] );
$image_id = $product->get_image_id();
$image_url = wp_get_attachment_image_url( $image_id, 'full');
$productsInCart[] = (object) [
"product_id" => $cart_item['product_id'],
"product_name" => $product->get_name(),
"product_regular_price" => $product->get_regular_price(),
"product_sale_price" => $product->get_sale_price(),
"thumbnail" => $image_url,
"qty" => $cart_item['quantity'],
"line_subtotal" => $cart_item['line_subtotal'],
"line_total" => $cart_item['line_total'],
];
}
update_user_meta(get_current_user_id(), '_woocommerce_persistent_cart_1', array('cart' => updatedCart, ));
$response = [
'status' => true,
'data' => $full_user_meta['cart'] != null ? $productsInCart : []
];
return rest_ensure_response($response);
}
function woocommerce_cart_list($param) {
$user_id = $param['user_id'];
$objProduct = new WC_Session_Handler();
$wc_session_data = $objProduct-> get_session($user_id);
// get the persistent cart may be _woocommerce_persistent_cart can be in ur case check in user_meta table
$full_user_meta = get_user_meta($user_id, ' _woocommerce_persistent_cart_1 ', true);
$productsInCard = [];
foreach($full_user_meta['cart'] as $cart_item) {
$product = wc_get_product( $cart_item['product_id'] );
$image_id = $product->get_image_id();
$image_url = wp_get_attachment_image_url( $image_id, 'full');
$productsInCart[] = (object) [
"product_id" => $cart_item['product_id'],
"product_name" => $product->get_name(),
"product_regular_price" => $product->get_regular_price(),
"product_sale_price" => $product->get_sale_price(),
"thumbnail" => $image_url,
"qty" => $cart_item['quantity'],
"line_subtotal" => $cart_item['line_subtotal'],
"line_total" => $cart_item['line_total'],
];
}
$response = [
'status' => true,
'data' => $full_user_meta['cart'] != null ? $productsInCart : []
];
return rest_ensure_response($response);
}
public function register_routes() {
register_rest_route(
$this->namespace,
'/addtocart',
array(
'methods' => 'POST',
'callback' => array( $this, 'woocommerce_add_to_cart'),
)
);
register_rest_route(
$this->namespace,
'/cart',
array(
'methods' => 'GET' ,
'callback' => array(
$this, 'woocommerce_cart_list'
),
)
);
}
}```

MVC Core and EF Core data grouping with Linq or something that can produce the desired result

I have a SQL query that return the result to List
public class WebTrafficStat
{
public string Group { get; set; }
public string Stat { get; set; }
public string Total { get; set; }
public bool? IsSubTotal { get; set; }
}
The result must be displayed as HTML Pivot table with either results grouped by "Stat" or "Group" field.
SQL result:
Desired result as HTML
I did the functions that does this PHP but now the project must be written in MVC Core
This is my PHP functions that I used currently
I grouped the array from SQL call results here:
function array_group_by(array $arr, $gElement, $gkey) {
$refined = $arr;
$result = array();
foreach ($arr[$gElement] as $data) {
$id = $data[$gkey];
if ( isset($data[$gkey]) && !empty($data[$gkey]) ) {
if (isset($result[$id])) {
$result[$id][] = $data;
} else {
$result[$id] = array($data);
}
}
}
if ( !empty($result) ) {
$refined[$gElement] = array();
foreach($result as $key=>$value) {
$refined[$gElement][] = array('name' => $key, 'childs' => $value);
}
$refined['grouped'] = 1;
}
return $refined;
}
And second function is
function grouped_array_to_html ($grouped, $groupField ){
$tableRows = array();
$columns = array();
$Row_Data = array();
if ( $grouped['grouped'] == 1 ){ // grouping found
$columns[] = 'Group';
// table columns/headers
foreach ($grouped['rows'] as $row) {
foreach ($row['childs'] as $child) {
if ( !in_array($child[$groupField], $columns ) ){
$columns[] = $child[$groupField];
}
}
}
//table rows
foreach ($grouped['rows'] as $a => $row) {
$tableRows[$a][] = $row['name'];
foreach ($row['childs'] as $c => $child) {
foreach ($columns as $x => $col){
if ( $col == $child[$groupField] )
{
$tableRows[$a][$x] = $child['total'];
break;
}
}
}
}
//Output Finale
foreach ( $tableRows as $b => $tr )
{
foreach ($columns as $c => $col) {
if ( !isset($tableRows[$b][$c]) )
$Row_Data[$b][$c] = '-';
else
$Row_Data[$b][$c] = $tableRows[$b][$c];
}
}
} else { // no grouping
foreach ($grouped['rows'] as $row) {
$Row_Data[] = $row;
}
}
$htmlOut = array(
'theaders' => $columns,
'trows' => $Row_Data
);
$grouped['rows']['html'] = $htmlOut;
return $grouped;
}
And I call PHP like this ... this gives me HTML table header rows and Body rows
In this case, I tell it to group by "Stat" column
$result = grouped_array_to_html( array_group_by($response, 'rows', 'group'), 'stat' );
So please how can I achieve same result using EF Core or Linq
I ended up approaching it like this:
if ((Model.WebReport != null) && Model.WebReport.Rows.Any())
{
var columns = Model.WebReport.Rows
.Select(c => (Model.GroupBy.Equals("Group") ? c.Stat : c.Group))
.Distinct()
.ToList();
columns.Insert(0, "Group");
var reportStat = Model.WebReport.Rows
.GroupBy(g => (Model.GroupBy.Equals("Group") ? g.Group : g.Stat))
.Select(x => new
{
Group = x.Key,
Stats = x.ToDictionary(y => (Model.GroupBy.Equals("Group") ? y.Stat : y.Group), y => y.Total)
});
Model.Columns = columns;
Model.ReportStats = reportStat.ToList();
}

Laravel-MongoDB, how order result by relevant

I use jenssegers/laravel-mongodb. I make scope
public function scopeWhereFullText($query, $search)
{
return $query->whereRaw(['$text' => ['$search' => $search]],['score'=>['$meta'=>'textScore']]);
}
How I can order By score field like in MongoDB js example:
db.products.find({$text:{$search:"SomeText"}},{score:{$meta:'textScore'}}).sort({score:{$meta:'textScore'}})
What is the solution without crutch:
public function scopeWhereFullText($query, $search)
{
$query->getQuery()->projections = ['score'=>['$meta'=>'textScore']];
return $query->whereRaw(['$text' => ['$search' => $search]]);
}
and in result
$products = Product::whereFullText($request->get('q',''))
->orderBy('score',['$meta'=>'textScore'])->get();
$max = $products->max('score');
$min = $products->min('score');
$products = $products->filter(function($item) use($max,$min){
return $item->score > ($max+$min)/2;
});
Use
$results = DB::connection()->collection('_User')->whereRaw(['$text' => ['$search' => 'SEARCH QUERY']])->project(['score'=>['$meta'=>'textScore']])->orderBy('score', ['$meta' => "textScore"])->limit(10)->get();

Zend update/insert (Zend_Db_Table_Abstract) doesn't work

I've got a problem with insert and update queries in Zend (Select is ok).
Definition of table:
class Application_Model_DbTable_Kpr1Data extends Zend_Db_Table_Abstract
{
protected $_name = 'kpr_kpr1_data';
}
Here is my data mapper (model)
class Application_Model_Kpr1DataMapper
{
protected $_dbTable;
public function setdbTable($dbTable) {
if(is_string($dbTable)){
$dbTable = new $dbTable();
}
if(!$dbTable instanceof Zend_Db_Table_Abstract ){
throw new Exception ('Invalid table data gateway provided.');
}
$this->_dbTable = $dbTable;
return $this;
}
public function getdbTable() {
if (null === $this->_dbTable){
$this->setdbTable('Application_Model_DbTable_Kpr1Data');
}
return $this->_dbTable;
}
public function save(Application_Model_Kpr1Data $kpr1data){
$data = array('id' => (int) $kpr1data->getId(),
'kpr1_plaza_id' => (int) $kpr1data->getPlaza(),
'kpr1_data' => new Zend_db_Expr("STR_TO_DATE('".$kpr1data->getDate()."', '%Y-%m-%d')"),
'kpr1_money_delivered' => (float) $kpr1data->getDelivered(),
'kpr1_money_transactions' => (float) $kpr1data->getTransactions(),
'kpr1_created' => new Zend_Db_Expr('CURDATE()')
);
$id = (int) $kpr1data->getId();
$table = $this->getdbTable();
if (is_null($id) && $id != 0) {
unset($data['id']);
$table->insert($data);
} else {
$table->update($data, array('id => ?', $id));
}
}
The last one is save function that should insert and update the data!
And this save is called from save action:
public function saveAction()
{
$plazaid = (int) $this->getRequest()->getParam('plaza');
$date = (string) $this->getRequest()->getParam('date');
$delivered = (string) $this->getRequest()->getParam('delivered');
$transactions = (string) $this->getRequest()->getParam('transactions');
$kpr1data = new Application_Model_Kpr1Data();
if ($plazaid && $date) {
$kpr1datamapper = new Application_Model_Kpr1DataMapper();
if($kpr1datamapper->findDatePlaza($date, $plazaid, $kpr1data)){
$kpr1data->setDelivered($delivered)
->setTransactions($transactions);
$kpr1datamapper->save($kpr1data);
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array("success"=>"true"));
} else {
$kpr1data->setDate($date);
$kpr1data->setDelivered($delivered);
$kpr1data->setTransactions($transactions);
$kpr1data->setPlaza($plazaid);
$kpr1datamapper->save($kpr1data);
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array("success"=>"true"));
}
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array(
//"success"=>"false",
"errorMsg"=>"Saving error"
));
} else {
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array(
//"success"=>"false",
"errorMsg"=>"Saving error"
));
}
return true;
}
Save action is called via JS, but even called directly through webbrowser it fails.
Behaviour: Application is running, and when debugger runs into update/insert line:
if (is_null($id) && $id != 0) {
unset($data['id']);
$table->insert($data);
} else {
$table->update($data, array('id => ?', $id));
}
it's redirecting to ErrorController.
I've check that:
1. firePHP is not showing this statements
2. MySQL database doesn't log this statement (I've checked via general_log feature).
I'm stucked. Help me please.
edit
$data=
array(6) (
[id] => (int) 0
[kpr1_plaza_id] => (int) 116
[kpr1_data] => Zend_Db_Expr object {
_expression => (string) STR_TO_DATE('2013-03-01', '%Y-%m-%d')
}
[kpr1_money_delivered] => (float) 120
[kpr1_money_transactions] => (float) 122
[kpr1_created] => Zend_Db_Expr object...
$kpr1data=
Application_Model_Kpr1Data object {
_plaza => (string) 116
_date => (string) 2013-03-01
_delivered => (string) 120.00
_transactions => (string) 122.00
_created => null
_id => null
_plazaname => null
}
This one should do insert.
And next one update:
Application_Model_Kpr1Data object {
_plaza => (string) 117
_date => (string) 2013-03-01
_delivered => (string) 120.00
_transactions => (string) 122.00
_created => (string) 2013-03-06 12:42:13
_id => (string) 79
_plazaname => (string) SPO Kraj...
in your saveAction() $this->view->result gets overwritten after if/else statement since your function does not return anything after (initially) setting $this->view->result.
Furthermore setting the first Saving error seems to be needless.
Try this:
public function saveAction()
{
$plazaid = (int) $this->getRequest()->getParam('plaza');
$date = (string) $this->getRequest()->getParam('date');
$delivered = (string) $this->getRequest()->getParam('delivered');
$transactions = (string) $this->getRequest()->getParam('transactions');
$kpr1data = new Application_Model_Kpr1Data();
if ($plazaid && $date) {
$kpr1datamapper = new Application_Model_Kpr1DataMapper();
if($kpr1datamapper->findDatePlaza($date, $plazaid, $kpr1data)){
$kpr1data->setDelivered($delivered)
->setTransactions($transactions);
$kpr1datamapper->save($kpr1data);
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array("success"=>"true"));
} else {
$kpr1data->setDate($date);
$kpr1data->setDelivered($delivered);
$kpr1data->setTransactions($transactions);
$kpr1data->setPlaza($plazaid);
$kpr1datamapper->save($kpr1data);
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array("success"=>"true"));
}
} else {
$this->_helper->layout->disableLayout();
$this->view->result = json_encode(array(
//"success"=>"false",
"errorMsg"=>"Saving error"
));
}
return true;
}
EDIT:
Try this as your save action:
public function save(Application_Model_Kpr1Data $kpr1data){
$table = $this->getdbTable();
if ($id == $kpr1data->getId()) {
$data = array('id' => (int) $id,
'kpr1_plaza_id' => (int) $kpr1data->getPlaza(),
'kpr1_data' => new Zend_Db_Expr("STR_TO_DATE('".$kpr1data->getDate()."', '%Y-%m-%d')"),
'kpr1_money_delivered' => (float) $kpr1data->getDelivered(),
'kpr1_money_transactions' => (float) $kpr1data->getTransactions(),
'kpr1_created' => new Zend_Db_Expr('CURDATE()')
);
$table->update($data, array('id => ?', $id));
} else {
[...]
$table->insert($data);
}
}

Database expression not used in query

Can anyone tell me why my expression is not used in the query below?
SELECT accountreset.* FROM accountreset WHERE (reset_id = '34') LIMIT 1
public function findByResetId($resetId, $model = null) {
$result = null;
if (isset($resetId)) {
$select = $this->getDao()->select(
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);
$select->where('reset_id = ?', $resetId);
$row = $this->getDao()->fetchRow($select);
if (null != $row) {
if (!($model instanceof Stage5_Model_PasswordResetter)) {
$model = new Stage5_Model_PasswordResetter();
}
// vul het model object
$model->setResetId($row->reset_id);
$model->setUserId($row->user_id);
$model->setExpiration($row->expiration);
$result = $model;
}
}
return $result;
}
Your Zend_Db_Expr should go into from() method instead of select()
$select = $this->getDao()
->select()
->from(
$this->getDao()->info('name'),
array('expiration' => new Zend_Db_Expr('UNIX_TIMESTAMP(expiration)'))
);