Laravel storing data after chuncking them - php

Hello there i have 3 tables
Companies
Coupons
Categories
Company table contains
id, name, logo
category contains
id, title, logo
coupons contains
id, title, terms, company_id, category_id
the last two are for relation ship between company , category modal and coupons modal
After that bieng said, here is the case
i have sent a request to my server using api that containes Company_id.
what i want to do is get all coupons that contain this Company_id , then from those coupons i want to take all Categories
what i tried
public function fetch_Categories($Company_id)
{
//getting all coupons that containes the current company id
$Coupons = Coupons::where('company_id' , $Company_id)->get();
//Coupons variable returns two coupons which is expected
foreach($Coupons as $Coupon){
$Categroies = Categories::find($Coupon->category_id);
}
}
ok you must have noticed the problem,
i am getting two coupons and in the future i will get more and i have to get the category from each one of them using category_id column , then return it using json as a collection of categories. but the question is how should i do that *_^
if it is not clear , i am getting two coupons and i should make foreach to store each category in my variable but when you put "=" sign then you will assign value for the variable and finally you will get one category which is the last one in the foreach , what i need is a way to store all the categories using the foreach and then return them to user using json

There are many ways to achieve this. Here is one:
$categoryIds = Coupons::where('company_id', $Company_id)->pluck('category_id')->unique();
$categories = Categories::whereIn('id', $categoryIds)->get();
This is also more efficient than the foreach loop, as it only uses a single query to fetch all categories.

Related

PHP laravel don't select duplicate fields shared in two tables

In my project I want to query orders. every food have a category and every category have a parent. so my problem is some orders have two type parent category. like Indian food and italian food in one order. I used select multiple element. and parent categories are shown inside it. one another item is all. so when user selects all parent categories the orders that have two type of categories like explained above it's shows more than 1 in table and I have no idea how to select only one of this duplicate fields.
my query code is :
if (isset($subset) && $subset!=""){
$query->leftJoin('z_food_orders','z_food_orders.order_id','=','z_orders.id')
->leftJoin('z_foods','z_food_orders.food_id','=','z_foods.id')
->leftJoin('z_food_cats','z_foods.cat_id','=','z_food_cats.id')
->leftJoin('z_res_subset','z_food_cats.parent_id','=','z_res_subset.id');
if (count($subset) == 1){
$query->where('z_res_subset.id',$subset);
}else{
$query->whereIn('z_res_subset.id',$subset);
}
}

Magento get unique values from custom database table

I created a custom module with a database table with the help of this article.
I have a program which syncs stock from my physical store to online store. Every time I sync the stock, I add the sku,name, sync data and time, also the qty to the custom database table. There can be multiple entries for the same sku in the table as the same product can be synced multiple times.
Initially I was taking a report of the unique entries from the database table using this, where I was only getting the skus.
$collections = Mage::getResourceModel('module/namespace_collection')->distinct(true)->addFieldToSelect('sku')->load();
foreach( $collections as $collection){
//add to csv
}
Now I want to get the sku and qty of the unique entries with the latest sync data and time for that particular sku. To get this I tried to use
$collections = Mage::getResourceModel('module/namespace_collection')->distinct(true)->addFieldToSelect('sku')->addFieldToSelect('qty')->addFieldToSelect('date')->load();
but I am getting all the entries in the custom table. Can some one help me out with this?
Get unique records from collection
$collection = Mage::getResourceModel('module/namespace_collection')
->getCollection()
->distinct(true)
->addAttributeToSelect('sku')
->load();
The above collection if not return desire data, try this
$collection = Mage::getResourceModel('module/namespace_collection')
->getCollection();
$collection->getSelect()->distinct(true);
But this will retrieve distinct values based on id. If you want to retrieve products using distinct sku values, you should group by "sku".
$collection->getSelect()->group('sku');
If you want to debug the query executed :
$collection->getSelect()->__toString();

How do I get the category ids that a product is in with respect to the store that I'm currently on

I'm on a product page and have the product object but when I try to get the category ids using:
$_product->getCategoryIds();
or:
$_product->getResource()->getAttribute('category_ids')->getFrontend()->getValue($_product);
it gets me all the category ids and I just want the ones for the store I'm on.
It's a multistore environment so hence my problem.
Everything else seems ok and the category list works fine.
This is my only problem.
Can anyone help?
Pretty similar to Alans answer, maybe a bit less looping:
$rootCategory = Mage::getModel('catalog/category')
->load(Mage::app()->getStore()->getRootCategoryId());
$sameStoreCategories = Mage::getResourceModel('catalog/category_collection')
->addIdFilter($product->getCategoryIds())
->addFieldToFilter('path', array('like' => $rootCategory->getPath() . '/%'))
->getItems();
var_dump(array_keys($sameStoreCategories));
This will always work. The ugly thing is that you still need to load the categories.
Here is a variation you can use if the flat category tables are enabled:
$sameStoreCategories = Mage::getResourceModel('catalog/category_flat_collection')
->addIdFilter($product->getCategoryIds())
->getItems();
var_dump(array_keys($sameStoreCategories));
Why does it work? Because the flat tables are indexed by store, and each flat table only contains the category entity records that are associated with that store groups root category.
So even though you are filtering by all category IDs associated with the product, the collection will only contain the categories present in the current store.
if you have millions of categories or millions of products or need collection of all products with all their categories - you can try next freak way (again works only after categories flat index rebuild):
in some installer or cron - create a a new table and keep it up to date with next request
for each store:
CREATE TABLE IF NOT EXISTS categories_X SELECT product_id, CONVERT(GROUP_CONCAT(category_id) USING utf8) as category_id FROM catalog_category_product where category_id in (select entity_id from catalog_category_flat_store_X) GROUP BY product_id
where X - is ID of store
write a model or direct request again to get all categories for required store and required product
This one is a little tricky, so if the following doesn't work it's probably the code and not you.
The problem is, as far as I can tell, Magento doesn't keep track of which categories are in which store. Instead, Magento keeps track of the root category for a particular store.
This means once we have a list of category IDs, we need to grab the root category for each, and then check if that root category matches the root category of the current store.
The following code should do that, but please test this with a variety of products
//get root category for current store
$store_root_id = Mage::app()->getStore()->getRootCategoryId();
//get category IDs from product
$ids = $product->getCategoryIds();
//load full cateogires
$categories = Mage::getModel('catalog/category')
->getCollection()
->addIdFilter($ids);
//filter out categories with different root
$category_ids = array();
foreach($categories as $cat)
{
//path property is 1/root_id/id/id
$parts = explode('/', $cat->getPath());
$one = array_shift($parts);
$root_id = array_shift($parts);
if($root_id == $store_root_id)
{
$category_ids[] = $cat->getId();
}
}
var_dump($category_ids);

Remap concatinated values in mysql db

I have 2 mysql tables one contains category mapping relationships between a supplier and our store: Basically what we call their categories eg ~ denotes sub category level:
Cateogry Mapping Relationship Table
Supplier Cat..........| Our Cat.....
dogs~leashes~long.....| pets~walking
dogs~leashes~long.....| pets~travel
dogs~leashes~short....| pets~walking
dogs~leashes~nylon....| pets~walking
dogs~feeding .........| pets~feeding
the other table contains supplier item ids with the categories that the supplier has the products in. Multiple categories are concatenated in the same field with a ','.
Such as the following:
Supplier Item Table
Supplier item ID...| Supplier item Categories
28374 ............| dogs~leashes~long,dogs~leashes~nylon
My task is to replace the item paths in the supplier list with the correct paths from our store category list so I can put them in our database.
So the result of the php / mysql function Im trying to build for the above data modification would be (I dont care if I run this in php or mysql which ever is easier to get the job done.):
Supplier item..| Supplier item Categories ..............| New item Categories
28374 ........| dogs~leashes~long,dogs~leashes~nylon ..|pets~travel,pets~walking
Im not sure how to handle the concatenated field and I would appreciate any help at all
thank you
write a query that selects id,cat from supplier item table
In a php loop split the category by ',' and do a select to get your category
write into a new table id/your category
check new table for validity
delete old table and rename new table

Tricky MySQL Insert and Update

I'm making a shopping cart for my website.
When an user add something into the cart it should insert item_id and quantity into the items column in my DB.
The item column should hold a string like this:
1:5;6:2;13:1
item_id:quantity;item_id:quantity and so on
The insert part I already got, but when the user wants to view the cart, the string needs to be split into an array and fetch the items from another table
Array example:
1 => 5,
6 => 2,
13 = 1
I'v tried using spliti(";" $raw);
But didn't get what I wanted.
And the same thing when the user updates/deletes a product from the cart..
When the user updates/deletes a product, it must search through the string inside items and find the current place of the product.
Any help would be appreciated :)
Since you are building your own cart do it correctly using a properly normalized schema. This means that you need to avoid "special" values which do more than 1 thing at the same time.
So the obvious improvement here is to have:
table users:
id
...
table products:
id
...
table cart_items:
user_id
product_id
quantity
CRUD queries will be very simple to implement then and also very fast.
First off, I don't think it's a good idea to have your items as a string in your order/cart table. You run into a lot of problems this way (you've already run into a couple).
It's better to have a hasMany relationship. Something along the likes of the design shown below is ideal.
Order Table : id, date, total, more, fields
OrderItem Table : id, order_id, item_id, value, more, fields //item_id is a ref to your Items/Product table
This allows you to link your items to your orders properly and you can do your inserts and updates without a problem.
As for your current question, you need to split it twice
$items = 1:5;6:2;13:1;
$items_arr = explode(';', $itemrs);
$new_items = array();
foreach ($iterms_arr as $item) {
$pieces = explode(':', $item);
//might want to do some error checking on whether the indices exist
$new_items[$pieces[0]] = $pieces[1];
}

Categories