I have basically the following table,
Categories
id name categories_id_categories
1 Clothes null
2 Shirts 1
3 Pants 1
4 Electronics null
5 Tv 4
The table stores categories and sub-categories, if the categories_id_categories is null theyre main categories else theyre sub-categories of the category with that id. I want to show this on a page so I created this functions on my Categories model:
public function getAllCategories()
{
$select = $this->select()
->where('categories_id_categories IS NULL');
return $this->fetchAll($select);
}
public function getAllSubCategories()
{
$select = $this->select()
->where('categories_id_categories IS NOT NULL');
return $this->fetchAll($select);
}
And on my controller:
$categories = new Model_DbTable_Categories();
$categoryList = $categories->getAllCategories();
$categoriesAll = array();
foreach ($categoryList->toArray() as $category) {
$subCategories = $categories->getSubCategoriesByCategory($category['id']);
$category['sub_categories'] = $subCategories->toArray();
$categoriesAll[] = $category;
}
$this->view->categoryList = $categoriesAll;
So categoryList is an array with all the categories and the key sub_categories is another array with all sub-categories. This works but I was wondering if there was a way to do it using objects instead of an array, and maybe using just one query instead of 2?
If I select all from the table I'd get categories and sub-categories but then I'd have to move some logic into the view to select the sub-categories I believe.
Thanks in advance!
Just put $id to getAllSubcategories and create getSubCategories in your model like this:
public function geSubCategories($id = null)
{
$select = $this->select();
if ( $id == null ) {
$select->where('categories_id_categories IS NOT NULL');
}
else {
$select->where('id = ?', $id);
}
return $this->fetchAll($select);
}
$sql = "SELECT * FROM TABLE_NAME WHERE ID = 1";
$rows = $db->fetchAll($sql);
//One row return array
echo $rows[0]['field_name'];
http://framework.zend.com/manual/1.12/en/zend.db.table.row.html
http://framework.zend.com/manual/1.12/en/zend.db.table.rowset.html
Related
I have tables that have the following structure, one product can have many skus:
product skus
id product_id
sku_prin sku
other fields other fields
If a search value is present in either sku_prin of products table or sku of skus table the row should be selected.
$search_value = "ramdom_value";
$query = product::query();
$result = $query->with(['skus' => function($q) use($search_value){
// this code won't work the orWhere cannot change the context of skus table
$q->where('sku', $search_value)->orWhere('products.sku_prin', $search_value)
}])->paginate(50);
Above is my failed attempt. How can accomplish what I want?
An approach is to use whereHas function of Eloquent
Consider you have the product and skus model like this
class Product extends Model
{
protected $table = 'product';
public function sku()
{
return $this->belongsTo('App\Skus', 'product_id', 'id');
}
}
class Skus extends Model
{
protected $table = 'skus';
public function products()
{
return $this->hasMany('App\Product', 'id', 'product_id');
}
}
You can obtain your data with Eloquent like this
$keyword = 'some keyword'
Product::where('sku_prin', '=', $keyword) // for product table
->orWhereHas('sku', function($query) use ($keyword) {
$query->where('sku', '=', $keyword); // for sku table
});
Or even more, do the fuzzy whereLike query with exploding keywords from a single string
$keywordString = 'keyword1 keyword2';
$keywords = explode(' ', $keywordString);
Product::where(function($query) use ($keywords) { // for product table
foreach ($keywords as $keyword)
{
$query->orWhere('sku_prin', 'like', "%$keyword%");
}
})
->orWhereHas('sku', function($query) use ($keywords) { // for sku table
foreach ($keywords as $keyword)
{
$query->orWhere('sku', '=', $keyword);
}
});
I've been on this for a while, what I want to do is to get the id of the selected value from a select box. Using this snippet, it doesn't get the id and I wonder why. I'm confused what what could be wrong
This code is to get the id of the selected value:
private static function compareCompany(ProductRequest $productRequest){
$companyPicked = $productRequest->companyname;
$listedCompanies = Company::where('user_id', '=', Auth::user()->id);
$companies = new Company;
if($companies->user_id === Auth::user()->id)
{
foreach($listedCompanies as $company) {
if($company->companyname === $companyPicked)
{
return $company->id;
}
}
}
}
This is to create a new product using the id returned for a company
public function store(ProductRequest $productRequest)
{
$product = new Product;
$company = new Company;
if($productRequest->isMethod('post')){
$product->user_id = Auth::user()->id;
$product->company_id = $this->compareCompany($productRequest);
$product->companyname = $productRequest->companyname;
$product->productname = $productRequest->productname;
$product->save();
return redirect()->route('companyindex')->with('message', 'Your question has been posted.');
}else{
return redirect('company-create')->withErrors($productRequest)->withInput();
}
}
THis is the view:
<p>{!! Form::select('companyname', array('' => 'Select a Company') + $listCompanies) !!} </p>
THis is the code used in binding the returned value to the view:
public function create()
{
$listCompanies = Company::where('user_id', '=', Auth::user()->id)->orderBy('companyname', 'desc')->lists('companyname', 'companyname')->toArray();
return view('product.create')
->with('listCompanies', $listCompanies);
}
I suspect that the problem is with your compareCompany method. There are a couple of issues there.
Here's your code (cleaned up a bit):
private static function compareCompany(ProductRequest $productRequest)
{
$companyPicked = $productRequest->companyname;
$listedCompanies = Company::where('user_id', '=', Auth::user()->id);
$companies = new Company;
if($companies->user_id === Auth::user()->id)
{
foreach($listedCompanies as $company) {
if($company->companyname === $companyPicked)
{
return $company->id;
}
}
}
}
And here are the issues:
$listedCompanies = Company::where('user_id', '=', Auth::user()->id);
This statement doesn't actually produce a list of companies. You need to add ->get() at the end, like this:
$listedCompanies = Company::where('user_id', '=', Auth::user()->id)->get();
$companies = new Company;
This creates a new, uninitialized instance of the Company model. On the next line you go on to check the user_id property of that instance, but it's not set to anything because it's brand new. So the first if() statement always fails. It's not clear what you're trying to do here, so I'm not sure how to fix this one. My guess is that you're trying to filter out only the companies that belong to the current user, but you've already done that with your Company::where(...)->get(), so this is not necessary.
Change ->lists('companyname', 'companyname') to ->lists('companyname', 'id')
It will return the id of the table of Company model.
I am new in magento i have tried to remove items in cart when call this event checkout_cart_product_add_after when i try this code nothing can doing. any body help me. thanks.
$myProductId=20;
$product = Mage::getModel('catalog/product')->setStoreId(Mage::app()->getStore()->getId())->load($myProductId);
$quote = Mage::getSingleton('checkout/session')->getQuote();
$cartItems = $quote->getItemByProduct($product);
if ($cartItems) { $quote->removeItem($cartItems->getId())->save();}
The ItemId (ID of an item in the cart) is not the same as the ProductId of the product it represents. Try iterating through the items in the cart until you find the one with the ProductId you want to remove:
$cartHelper = Mage::helper('checkout/cart');
$items = $cartHelper->getCart()->getItems();
foreach ($items as $item) {
if ($item->getProduct()->getId() == $productId) {
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
}
}
Please try as described above.
Below code work for me you can try this you can call this function using ajax or post method put this function inside your controller and call it. pass the customer id and product it to it
public function removeCartAction()
{
$productId = trim($_POST['productId']);
$customer = trim($_POST['requesterId']);
if ($customer) {
$storeId = Mage::app()->getWebsite(true)->getDefaultGroup()->getDefaultStoreId();
// get quote table cart detail of all customer added
$quote = Mage::getModel('sales/quote')->setStoreId($storeId)->loadByCustomer($customer);
if ($quote) {
$collection = $quote->getItemsCollection(false);
if ($collection->count() > 0) {
foreach( $collection as $item ) {
if ($item && $item->getId()) {
$quote->removeItem($item->getId());
$quote->collectTotals()->save();
}
}
}
}
}
}
To remove item by specific item_id from cart(quote) you can use this:
$cart = Mage::getModel('checkout/session')->getQuote();
$cartHelper = Mage::helper('checkout/cart');
$items = $cart->getAllVisibleItems();
foreach($items as $item):
if($item->getItemId() == $id):
$itemId = $item->getItemId();
$cartHelper->getCart()->removeItem($itemId)->save();
break;
endif;
endforeach;
Execute this you will get the output
$product = $observer->getEvent()->getProduct();
$cart = Mage::getSingleton('checkout/cart');
foreach ($cart->getQuote()->getItemsCollection() as $_item) {
if ($_item->getProductId() == $productId) {
$_item->isDeleted(true);
//Mage::getSingleton('core/session')->addNotice('This product cannot be added to shopping cart.');
}
}
I'm using the zend framework with centurion and I'm having a problem with my form. I have fields num_ordre and code, both of which are primary keys and I have columns in my table named conca, it's the concatenation of two fields, num_ordre and code.
My question is, in my method post, I want to test if the concatanation of num_ordre and code already exists in my database; but the problem is how to take a value of to fields before posting it.
This is my code
public function postAction(){
$this->_helper->viewRenderer->setNoRender(TRUE);
$user = new Param_Model_DbTable_Verification();
$form= $this->_getForm();
$form->getElement('Num_ordre')->addValidator(new Zend_Validate_Db_NoRecordExists('verifications','Num_ordre'));
$form->getElement('Num_ordre')->setRequired(true);
$posts = $this->_request->getPost();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$row=$user->createRow();
$row->code=$this->_getParam('code');
$row->Num_ordre=$this->_getParam('Num_ordre');
$row->Libelle_champ=$this->_getParam('Libelle_champ');
$row->comparaison=$this->_getParam('comparaison');
$row->formule=$this->_getParam('formule');
$row->obligatoire=$this->_getParam('obligatoire');
$row->Req_traduction=$this->_getParam('Req_traduction');
$row->tolerance_erreur=$this->_getParam('tolerance_erreur');
$row->Mess_erreur=$this->_getParam('Mess_erreur');
$row->conca=$this->_getParam('Num_ordre').$this->_getParam('code');
$row->save();
if( isset ($posts['_addanother'])){
$_form = $this->_getForm();
$_form->removeElement('id');
$this->_helper->redirector('new','admin-verification');
}
else
$this->_helper->redirector(array('controller'=>'Admin-verification'));
}else{
parent::postAction();
}
}}
How about you just check it like this ?
public function postAction(){
$this->_helper->viewRenderer->setNoRender(TRUE);
$user = new Param_Model_DbTable_Verification();
$form= $this->_getForm();
$form->getElement('Num_ordre')->addValidator(new Zend_Validate_Db_NoRecordExists('verifications','Num_ordre'));
$form->getElement('Num_ordre')->setRequired(true);
$posts = $this->_request->getPost();
if ($this->getRequest()->isPost()) {
$formData = $this->getRequest()->getPost();
$mdl = new Model_Something(); //Call your model so you can test it
//Add a condition here
if ($form->isValid($formData) && $mdl->uniqueConcatenated($this->_getParam('num_ordre'), $this->_getParam('code')) {
$row=$user->createRow();
/**truncated, keep your existing code here**/
}
}
}
Then in your model Model_Something
public function uniqueConcatenated($numOrder, $code) {
$concatenated = $numOrder.$code;
//Check for the existence of a row with the concatenated field values
$select = $this->select();
$select->where('concatenatedField = '.$concatenated);
$row = $this->fetchRow($select);
return $row;
}
Hope this helps
You could manually call isValid on the validator:
$formData = $this->getRequest()->getPost();
if ($form->isValid($formData)) {
$formValues = $form->getValues();
$uniqueValidator = new Zend_Validate_Db_NoRecordExists('verifications','conca');
if ($uniqueValidator->isValid($formValues['Num_ordre'] . $formValues['Num_ordre'])) {
// valid
} else {
// not unique
}
}
untested code
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)'))
);