How to delete quantity and update in database using laravel? - laravel

When I am inserting quantity in database, I want to update the quantity in the another table. This is what I have tried so far,
public function insertData(Request $request)
{
$userProduct = new UserProduct();
$localStorageData = $request->input('localStorageData');
$productData = json_decode($localStorageData);
print_r($productData);
foreach ($productData as $value) {
$data_array['qty'] = $value->productQty;
$data_array['fk_p_id'] = $value->productId;
$data_array['fk_user_id'] = $request->fkUserId;
UserProduct::insert($data_array);
}
}
In product table I have "id","p_qty"

without updating it, you can get the total quantity by doing sum operation for the main object
$localStorageData = $request->input('localStorageData');
$productData = json_decode($localStorageData);
$userProduct = new UserProduct();
$userProduct->p_qty = collect($productData)->sum('productQty')

You can use two methods to accomplish this in Laravel, using model on created and observers:
<?php
namespace App\Observers;
use App\Models\Transaction;
use Illuminate\Support\Str;
class UserProductObserver
{
public function created(UserProduct $userProduct)
{
$product = $userProduct->product;
$product->p_qty= $product->p_qty+ $userProduct->qty
$product->save();
}
}

Related

Can't filter data from database using getSelect()->where() Magento 2

I am currently working with magento 2.2.1 and I am having a weird problem. I am trying to get a set of data from database and display it on admin grid. I want to take records for a specific agent ID so i have a variable that has the value of the agent id. When i pass this variable as parameter to$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId); it wont display anything but if i replace $this->givenAgentId with it's value, for example with 4, it works perfectly!
This is my class:
<?php
namespace vendor\plugin\Ui\Component\Listing\DataProviders\Atisstats\Coupons;
use \vendor\plugin\Model\ResourceModel\Coupons\CollectionFactory;
use \Magento\Framework\Registry;
class Listing extends \Magento\Ui\DataProvider\AbstractDataProvider {
protected $_registry;
protected $givenAgentId = 0;
public function __construct(
Registry $registry,
$name,
$primaryFieldName,
$requestFieldName,
CollectionFactory $collectionFactory,
array $meta = [],
array $data = []
) {
parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
$this->_registry = $registry;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resource = $objectManager->get('\Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$select = $connection->select()
->from(
['amasty_perm_dealer'],
['user_id']
);
$data = $connection->fetchAll($select);
foreach ($data as $dealerId) {
if ($dealerId['user_id'] == $this->_registry->registry('admin_session_id')) {
$this->givenAgentId = intval($this->_registry->registry('admin_session_id'));
}
}
if ($this->givenAgentId != 0) {
$this->collection->getSelect()->where('agent_id = ?', $this->givenAgentId);
} else {
$this->collection = $collectionFactory->create();
}
}
}
I have stuck here for hours!
I fixed this problem! First of all it was Registry class causing the problem so I used
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$resourceUserId = $objectManager->get('\Magento\Backend\Model\Auth\Session');
to get the user id from session and used it below to check the user! For some reason the registry object was modifying the variable holding the current users id!
I post the answer just in case someone get stuck with this kind of problem !

Laravel 5.1 Command empty table

I'm using a command to add products from an API to my database using the following code
class UpdateCatalog extends Command {
protected $name = 'catalog:update';
protected $description = 'Command description.';
public function __construct()
{
parent::__construct();
}
public function fire()
{
$products = Api::productsGetProducts();
foreach($products as $product)
{
$detail = Api::productsGetProduct($product['id']);
$product = new Product();
$product->id = $detail->getId();
$product->external_id = $detail->getExternalId();
$product->name = $detail->getName();
$product->description = $detail->getDescription();
$product->thumbnail = $detail->getThumbnail();
$product->price = $detail->getPrices()[0]['price_excl_vat'];
$product->vat = $detail->getVat();
$product->save();
}
}
}
Now I'm wondering if it's possible to empty the table prior to filling it again.
Thank you!
Do you mean you want to empty your Product database table?
This can be done with truncate like this:
Product::truncate();
Note: This will remove all rows and reset the auto-incrementing ID to zero

CakePHP serializing objects

I'm stuck with the following problem:
I have a class CartItem. I want to store array of objects of CartItem in session (actually i'm implementing a shopping cart).
class CartItem extends AppModel{
var $name = "CartItem";
var $useTable = false;
}
I tried this:
function addToCart(){
$this->loadModel("Cart");
$this->layout = false;
$this->render(false);
$cart = array();
$tempcart = unserialize($this->Session->read("cart"));
if(isset($tempcart)){
$cart = $tempcart;
}
$productId = $this->request->data("id");
if(!$this->existsInCart($cart, $productId)){
$cartItem = new Cart();
$cartItem->productId = $productId;
$cartItem->createdAt = date();
$cart[] = $cartItem;
$this->Session->write("cart", serialize($cart));
echo "added";
}
else
echo "duplicate";
}
I think I'm writing these lines wrong:
$tempcart = unserialize($this->Session->read("cart"));
$this->Session->write("cart", serialize($cart));
as I'm not getting data from the session.
You are trying to add the whole Cart object to the session.
You should just add an array, like
$cart[] = array(
'productId' => $productId,
'createdAt' => date('Y-m-d H:i:s')
);
If you need to add an object to a session, you can use __sleep and __wakeup magic functions but I think in this case it's better to just add only the product id and date to the session.

Magento. How to link store_id to the attribute in the custom EAV Model

I am using this tutorial on adding new EAV Model in Magento:
http://inchoo.net/ecommerce/magento/creating-an-eav-based-models-in-magento/
Everything works fine except all my attributes are saving with "store_id = 0" when I do this part of code:
$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();
I am wondering is there any clear way to set store ID on save EAV Entity Attributes.
Thanks.
You can only set values for a specific store only after you added the values for store id 0.
Here is an example.
//create default values
$phonebookUser = Mage::getModel('inchoo_phonebook/user');
$phonebookUser->setFristname('John');
$phonebookUser->save();
//remember the id of the entity just created
$id = $phonebookUser->getId();
//update the name for store id 1
$phonebookUser = Mage::getModel('inchoo_phonebook/user')
->setStoreId(1)
->load($id); //load the entity for a store id.
$phonebookUser->setFristname('Jack'); //change the name
$phonebookUser->save(); //save
I have override the functions in my resource model to work with store_id and it is worked for me but I suggest that this is not the best solution.
protected function _saveAttribute($object, $attribute, $value)
{
$table = $attribute->getBackend()->getTable();
if (!isset($this->_attributeValuesToSave[$table])) {
$this->_attributeValuesToSave[$table] = array();
}
$entityIdField = $attribute->getBackend()->getEntityIdField();
$data = array(
'entity_type_id' => $object->getEntityTypeId(),
$entityIdField => $object->getId(),
'attribute_id' => $attribute->getId(),
'store_id' => $object->getStoreId(), //added this
'value' => $this->_prepareValueForSave($value, $attribute)
);
$this->_attributeValuesToSave[$table][] = $data;
return $this;
}
protected function _getLoadAttributesSelect($object, $table)
{
$select = $this->_getReadAdapter()->select()
->from($table, array())
->where($this->getEntityIdField() . ' =?', $object->getId())
->where('store_id in (?)', array($object->getStoreId(), 0)); //added this
return $select;
}
also I have added this code to the constructor of my entity model:
if (Mage::app()->getStore()->isAdmin()) {
$this->setStoreId(Mage::app()->getRequest()->getParam('store', 0));
}
else{
$this->setStoreId(Mage::app()->getStore()->getId());
}
Override the _getDefaultAttributes() method in your resource model like this:
protected function _getDefaultAttributes()
{
$attributes = parent::_getDefaultAttributes();
$attributes[] = "store_id";
return $attributes;
}
This should work if you have only one value for store_id per your model's entity.

zend Pagination without fetching query again for each page

Is it possible to use zend pagination without calling the query every time i request a page from the pager?
When I hit a page number from the pager a request to the zzAction below is done and the query is fetched again. My query is huge and I don't want to fetch the query all over again. Am I missing something in the code.
Code:
Controller:
public function getOnePageOfEntries($array, $page=1) {
$paginator = Zend_Paginator::factory($array);
$paginator->setItemCountPerPage(6);
$paginator->setCurrentPageNumber($page);
return $paginator;
}
public function zzAction() {
...
$tt= $this->yyObject->xx(....);
$paginator = $this -> getOnePageOfEntries($tt, $page);
$this->view->paginator = $paginator;
}
Model:
public function xx(...){
try{
...
$stmt = $this->prepare("CALL sp_yy(...)");
....
$stmt->execute();
$result = $stmt->fetchAll();
if (is_null($result)) {
return null;
}
return $result;
}catch (ErrorsException $obj){
echo $obj;exit;
}//end try
}
View:
<?php
$config = Zend_Registry::get('appsConfig');
?>
<?php if (count($this->paginator)){ ?>
<?php foreach($this->paginator as $cc){ ?>
<?php echo $cc['id'] . '/';?>
<?php } ?>
<?php } ?>
<?php echo $this->paginationControl($this->paginator,
'Sliding','ff/my_pagination_control.phtml'); ?>
using Zend_Paginator_Adapater_DbSelect();
example:
$adapter = new Zend_Paginator_Adapter_DbSelect($data); //$data is database query
$pagination = new Zend_Paginator($adapter);
See more here:
Zend_Paginator_Adapter_DbSelect
Your current code artificially limits the utility of the array adapter and forces you to execute the whole query for every page. What you need to accomplish in your controller actions that consume this paginator is to only execute the query if the data doesn't already exist. Maybe something similar to:
//consider this to psuedocode as it has not been tested a represents an idea
public function zzAction()
{
//get page number
$page = $this->getRequest()->getParam('page');
//set session namespace, probably better to do this in init() method or bootstrap
$session = new Zend_Session_Namespace('paged')
//test for presence of persisted array
if (!isset($session->paginator)) {
//perform query
$arrayToPage = $this->yyObject->xx(....);
//persist result array
$session->paginator = $arrayToPage;
} else {
//retrieve persisted array
$arrayToPage = $session->paginator;
}
$paginator = $this -> getOnePageOfEntries($arrayToPage, $page);
$this->view->paginator = $paginator;
}
Using the DbTableSelect or DbSelect paginator adapter is often far more effiecient as it only queries for the data need to populate a specific page. This is very useful when your user wants to go form page 1 to page 7 ...
Another consideration when using a paginator is custom entity models. This is fairly easy to deal with in ZF:
<?php
class Record_Model_Paginator_Record extends Zend_Paginator_Adapter_DbTableSelect
{
//override getItems to customize the adapter to use a specific mapper to create entities
public function getItems($offset, $itemCountPerPage)
{
$rows = parent::getItems($offset, $itemCountPerPage);
$record = array();
foreach ($rows as $row) {
//initiate mapper
$recordEntity = new Application_Model_Mapper_Record();
//create entity models
$record[] = $recordEntity->createEntity($row);
}
//returns an array of objects, similar to a Zend_Db_Rowset object
return $record;
}
}
I hope this helps.

Resources