Kohana 3.2 'advance' ORM joins - php

This is Database ERD that I use in application. I'm using Kohana 3.2. What I want to achieve is to generate menu for currently logged user. Each user can have many roles, so based on that user should get menu populated with modules (that are in relation with menu and user).
I have achieve this through several foreach loops. Is it possible to do this using ORM ?
*Table 'Modules' represents menu items.
Edit: this is my current code.
$conf_modules = Kohana::$config->load('modules');
$user_roles = $user->roles->find_all();
$result = array();
$array = array();
foreach($user_roles as $user_role)
{
$menus = $user_role->menus->find_all();
$modules = $user_role->modules->find_all();
}
foreach($menus as $menu)
{
$m = $menu->modules->find_all();
$result[]['name'] = $menu->name;
foreach ($m as $a)
{
foreach ($modules as $module)
{
if($a->name == $module->name)
{
foreach ($conf_modules as $key => $value)
{
if($module->name == $key)
{
$array = array(
'module_name' => $module->name,
'text' => $module->display_desc,
'url' => $value['url'],
);
}
}
}
}
array_push($result, $array);
}
}

I think this should be good solution.
$user = Auth::instance()->get_user();
$user_roles = $user->roles->find_all();
$conf_modules = Kohana::$config->load('modules');
$role_modules = ORM::factory('module')
->join('roles_modules')
->on('roles_modules.module_id','=','module.id')
->where('role_id','IN',$user_roles->as_array(NULL,'id'))
->find_all();
$role_menus = ORM::factory('menu')
->join('roles_menus')
->on('roles_menus.menu_id','=','menu.id')
->where('role_id','IN',$user_roles->as_array(NULL,'id'))
->find_all();
$result = array();
foreach ($role_menus as $role_menu)
{
$menu_modules = $role_menu->modules->find_all();
if ( ! isset($result[$role_menu->name]))
$result[$role_menu->name] = array('name' => $role_menu->name);
foreach ($menu_modules as $menu_module)
{
foreach ($role_modules as $role_module)
{
if($menu_module->name == $role_module->name)
{
foreach ($conf_modules as $key => $value)
{
if ($key == $role_module->name)
{
$result[$role_menu->name]['modules'][]['data'] = array('name' => $role_module->display_desc, 'url' => $value['url']);
}
}
}
}
}
}
return array_values($result);

Related

How to write category and subcategory with foreach?

I have a database category table , With 3 fields id,name,cate . And I put it into array
$select = $this->db->get_where('cate',array('cate >'=> 0))->result_array();
I want to write a foreach that
if (cate == 1) : This is the main menu
else if (cate == main menu id) : this is subcategory
Here is what I have tried
foreach ($select as $key => $value) {
$id = $value['id'];
$name = $value['name'];
$cate = $value['cate'];
}
I'm sorry for my poor English
it's my solution:
$categoriesHierchy = [];
foreach ($categories as $mainCategory) {
$childNode = [
'id' => $mainCategory->getID(),
'polishName' => $mainCategory->getPolishName(),
'children' => findChildrenOfCategory($mainCategory)
];
array_push($categoriesHierchy, $childNode);
}
public function findChildrenOfCategory($category)
{
$children = [];
if (count($category->getChildren()) > 0) {
foreach ($category->getChildren() as $child) {
$childCategories = findChildrenOfCategory($child);
$childNode = [
'id' => $child->getID(),
'polishName' => $child->getPolishName(),
'children' => $childCategories
];
array_push($children, $childNode);
}
}
return $children;
}
foreach ($select as $value) { //selecting each row/element
$cate = $value['cate']; //grabbing column values
$name = $value['name'];
If($cate == 1){ //no need of cate == main cate id
echo $name." is a main";
}else{
echo $name." is a sub";
}
}

php : csv import to multiple table is taking too long

i am using csv importer library to load bulk of products into mysql database with codeigniter. csv file has some column names from one table like name, price and some column names from another table like categories. it inserts name and price to first table and categories will be inserted after we got id from first table, so category will go with id of the product. but this is taking too long to process the csv file (1000 entries = 2 minutes). the code i have put is
$csv_file_data = $this->csvimport->get_array($_FILES['csv']['tmp_name']);
foreach ($csv_file_data as $csv_data) {
$required = array(
'name' => $csv_data['name'],
'price' => $csv_data['price']
);
foreach ($required as $key => $value) {
$this->db->set($key, $value);
}
$categories= array();
foreach ($csv_data as $key => $value) {
if(strstr($key, 'categories')) {
$category = explode('|', $value);
for($i = 0; $i < sizeof($category); $i++) {
array_push($categories, $category[$i]);
}
}
}
$this->db->insert('first_table');
$id = $this->db->insert_id();
foreach ($categories as $metatag) {
$this->db->set('productid', $id);
$this->db->set('category', $metatag);
$this->db->insert('second_table');
}
}
but it is taking too long to process only 1000 entries, how to optimize this to process 5000 entries in less than 20-30 seconds ?
I believe this is what you're after ...
$csv_file_data = $this->csvimport->get_array($_FILES['csv']['tmp_name']);
foreach ($csv_file_data as $csv_data) {
$required = array(
'name' => $csv_data['name'],
'price' => $csv_data['price']
);
$this->db->set($required);
$categories = array();
foreach ($csv_data as $key => $value) {
if (strstr($key, 'categories')) {
$category = explode('|', $value);
for ($i = 0; $i < sizeof($category); $i++) {
$categories[] = $category[$i];
}
}
}
$this->db->insert('first_table');
$bulk = array();
$id = $this->db->insert_id();
foreach ($categories as $metatag) {
$bulk[] = array(
'category' => $metatag,
'productid' => $id,
);
}
$this->db->insert_batch('table2', $bulk);
}
Note the use of insert_batch which will dramatically improve your speed and also you can give set() an array.
Can you try a version like this and tell me if this is working and return me the time for 100 rows ?
$bulk = [];
$csv_file_data = $this->csvimport->get_array($_FILES['csv']['tmp_name']);
$required = [];
foreach ($csv_file_data as $csv_data) {
$bulk = [];
$id = $this->db->insert_id();
$required[] = [
'name' => $csv_data['name'],
'price' => $csv_data['price'],
];
foreach ($csv_data as $key => $value) {
if (false !== strpos($key, 'categories')) {
$category = explode('|', $value);
foreach ($category as $metatag) {
$bulk[] = [
'category' => $metatag,
'productid' => $id,
];
}
}
}
}
$this->db->insert_batch('first_table', $required);
$this->db->insert_batch('second_table', $bulk);

Yii2 Update Parent Child

I have a structure table like this
I want to change record data field goid = 1, but I as you can see my code bellow, there's limit looping. Is there a better way to do it?
public function actionShareGoid($folder)
{
$one = DokumenFolder::findOne($folder);
$one->goid = '1';
$one->update(false);
$models_1 = DokumenFolder::find()->where(['parent_id'=>$one->id])->all();
foreach ($models_1 as $key_1 => $model_1) {
$model_1->goid = '1';
$model_1->update(false);
$models_2 = DokumenFolder::find()->where(['parent_id'=>$model_1->id])->all();
foreach ($models_2 as $key_2 => $model_2) {
$model_2->goid = '1';
$model_2->update(false);
$models_3 = DokumenFolder::find()->where(['parent_id'=>$model_2->id])->all();
foreach ($models_3 as $key_3 => $model_3) {
$model_3->goid = '1';
$model_3->update(false);
$models_4 = DokumenFolder::find()->where(['parent_id'=>$model_3->id])->all();
foreach ($models_4 as $key_4 => $model_4) {
$model_4->goid = '1';
$model_4->update(false);
}
}
}
}
return $this->redirect(Yii::$app->request->referrer);
}
Thanks to someone, I got the answer. ^_^
So here it is...
public function folderParent($id)
{
$models = DokumenFolder::find()->where(['parent_id'=>$id])->all();
foreach ($models as $key => $model) {
$model->goid = '1';
$model->update(false);
}
}
public function actionShareGoid($id)
{
$models = DokumenFolder::find()->where(['parent_id'=>$id])->all();
foreach ($models as $key => $model) {
$this->folderParent($model->id);
}
return $this->redirect(Yii::$app->request->referrer);
}

Reduce amount of queries and increase performance for categories and subcategories queries

EDIT 3: Got it down to 300-500 ms by changing flatten method to only merge arrays if not empty.
EDIT 2: Got it down to 1.6 seconds by only calling array_replace for non empty array. Now all that is left to do is optimize the function sort_categories_and_sub_categories. That is NOW the bottleneck. If I remove that I am down to 300ms. Any ideas?
get_all_categories_and_sub_categories
foreach(array_keys($categories) as $id)
{
$subcategories = $this->get_all_categories_and_sub_categories($id, $depth + 1);
if (!empty($subcategories))
{
$categories = array_replace($categories, $subcategories);
}
}
EDIT
I improved performance by over 50% (6 seconds --> 2.5 seconds) by doing a cache in the get_all method. It reduces the amount of queries to 1 from 3000. I am still wondering why it is slow.
I have the following method for getting categories and nested sub categories. If a user has a couple hundred (or thousand) top level categories it does a bunch of queries for each category to find the children. In one case I have 3000 categories and it did 3000 queries. Is there a way to optimize this to do less queries? OR should I just check to see if they have a lot of categories NOT to try to show nested too.
function get_all_categories_and_sub_categories($parent_id = NULL, $depth = 0)
{
$categories = $this->get_all($parent_id);
if (!empty($categories))
{
foreach($categories as $id => $value)
{
$categories[$id]['depth'] = $depth;
}
foreach(array_keys($categories) as $id)
{
$categories = array_replace($categories, $this->get_all_categories_and_sub_categories($id, $depth + 1));
}
return $categories;
}
else
{
return $categories;
}
}
function get_all($parent_id = NULL, $limit=10000, $offset=0,$col='name',$order='asc')
{
static $cache = array();
if (!$cache)
{
$this->db->from('categories');
$this->db->where('deleted',0);
if (!$this->config->item('speed_up_search_queries'))
{
$this->db->order_by($col, $order);
}
$this->db->limit($limit);
$this->db->offset($offset);
foreach($this->db->get()->result_array() as $result)
{
$cache[$result['parent_id'] ? $result['parent_id'] : 0][] = array('name' => $result['name'], 'parent_id' => $result['parent_id'], 'id' => $result['id']);
}
}
$return = array();
$key = $parent_id == NULL ? 0 : $parent_id;
if (isset($cache[$key]))
{
foreach($cache[$key] as $row)
{
$return[$row['id']] = array('name' => $row['name'], 'parent_id' => $row['parent_id']);
}
return $return;
}
return $return;
}
function sort_categories_and_sub_categories($categories)
{
$objects = array();
// turn to array of objects to make sure our elements are passed by reference
foreach ($categories as $k => $v)
{
$node = new StdClass();
$node->id = $k;
$node->parent_id = $v['parent_id'];
$node->name = $v['name'];
$node->depth = $v['depth'];
$node->children = array();
$objects[$k] = $node;
}
// list dependencies parent -> children
foreach ($objects as $node)
{
$parent_id = $node->parent_id;
if ($parent_id !== null)
{
$objects[$parent_id]->children[] = $node;
}
}
// clean the object list to make kind of a tree (we keep only root elements)
$sorted = array_filter($objects, array('Category','_filter_to_root'));
// flatten recursively
$categories = self::_flatten($sorted);
$return = array();
foreach($categories as $category)
{
$return[$category->id] = array('depth' => $category->depth, 'name' => $category->name, 'parent_id' => $category->parent_id);
}
return $return;
}
static function _filter_to_root($node)
{
return $node->depth === 0;
}
static function _flatten($elements)
{
$result = array();
foreach ($elements as $element)
{
if (property_exists($element, 'children'))
{
$children = $element->children;
unset($element->children);
}
else
{
$children = null;
}
$result[] = $element;
if (isset($children))
{
$flatened = self::_flatten($children);
if (!empty($flatened))
{
$result = array_merge($result, $flatened);
}
}
}
return $result;
}

Split an array into sub arrays

I would like to split an array:
$o = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]');
based on the color attribute of each item, and fill corresponding sub arrays
$a = array("green", "yellow", "blue");
function isGreen($var){
return($var->color == "green");
}
$greens = array_filter($o, "isGreen");
$yellows = array_filter($o, "isYellow");
// and all possible categories in $a..
my $a has a length > 20, and could increase more, so I need a general way instead of writing functions by hand
There doesn't seem to exist a function array_split to generate all filtered arrays
or else I need a sort of lambda function maybe
You could do something like:
$o = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]');
$greens = array_filter($o, function($item) {
if ($item->color == 'green') {
return true;
}
return false;
});
Or if you want to create something really generic you could do something like the following:
function filterArray($array, $type, $value)
{
$result = array();
foreach($array as $item) {
if ($item->{$type} == $value) {
$result[] = $item;
}
}
return $result;
}
$o = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]');
$greens = filterArray($o, 'color', 'green');
$yellows = filterArray($o, 'color', 'yellow');
In my second example you could just pass the array and tell the function what to filter (e.g. color or some other future property) on based on what value.
Note that I have not done any error checking whether properties really exist
I would not go down the road of creating a ton of functions, manually or dynamically.
Here's my idea, and the design could be modified so filters are chainable:
<?php
class ItemsFilter
{
protected $items = array();
public function __construct($items) {
$this->items = $items;
}
public function byColor($color)
{
$items = array();
foreach ($this->items as $item) {
// I don't like this: I would prefer each item was an object and had getColor()
if (empty($item->color) || $item->color != $color)
continue;
$items[] = $item;
}
return $items;
}
}
$items = json_decode('[{"id":"1","color":"green"},{"id":"2","color":"green"},{"id":"3","color":"yellow"},{"id":"4","color":"green"}]');
$filter = new ItemsFilter($items);
$greens = $filter->byColor('green');
echo '<pre>';
print_r($greens);
echo '</pre>';
If you need more arguments you could use this function:
function splitArray($array, $params) {
$result = array();
foreach ($array as $item) {
$status = true;
foreach ($params as $key => $value) {
if ($item[$key] != $value) {
$status = false;
continue;
}
}
if ($status == true) {
$result[] = $item;
}
}
return $result;
}
$greensAndID1 = splitArray($o, array('color' => 'green', 'id' => 1));

Categories