Yii 2 Get NULL when select data with where in array - mysql

I have an array $areaID :
array(3) {
[0]=> array(1) { ["idarea"]=> int(56) }
[1]=> array(1) { ["idarea"]=> int(67) }
[2]=> array(1) { ["idarea"]=> int(116)}
}
Then, I want to select from MySQL database to get data where $areaID in array. My query:
$data = (new \yii\db\Query())
->select('*')
->from('store')
->join('LEFT JOIN','detail_area','detail_area.idareaV = store.idareas')
->join('LEFT JOIN','detail_user','detail_user.id_area = detail_area.idarea')
->where(['in','detail_area.idarea',$areaID])
->all()
But when running,, i got my $areaID is null. Like this :
SELECT * FROM `store` LEFT JOIN `detail_area` ON detail_area.idareaV = store.idareas LEFT JOIN `detail_user` ON detail_user.id_area = detail_area.idarea WHERE (`detail_area`.`idarea` IN (NULL, NULL, NULL))
Can you help me? Thank you ...

Use
->where([
'detail_area.idarea' => array_values(
\yii\helpers\ArrayHelper::map($areaID, 'idarea', 'idarea')
)
])

Related

How to avoid _matchingData and get a specific value instead

In the Orders Table Model I need the category ids of the products associated with the order
Model/Table/OrdersTable.php
public function updateQuantityForInventoryItems(array $orders_items): void
{
$ordersItemsIds = [];
foreach ($orders_items as $orders_item) {
array_push($ordersItemsIds, $orders_item->product_id);
}
$catIds = $this->find('ordersItemsCategories', ['ordersItemsIds' => $ordersItemsIds])->toArray();
dd($catIds);
$InventoriesTable = TableRegistry::getTableLocator()->get('Inventories');
$InventoriesTable->updateQuantityForInventoryItems('orders', $catIds);
}
public function findOrdersItemsCategories(Query $query, array $options): Query
{
$query = $this->OrdersItems->Products
->find()
->select(['Products.id','CategoriesProducts.category_id'])
->matching(
'CategoriesProducts', function (Query $q) use ($options) {
return $q->where([
'CategoriesProducts.product_id IN' => $options['ordersItemsIds'],
]);
});
return $query->hydrate(false);
}
the generated SQL query
SELECT Products.id AS `Products__id`, CategoriesProducts.category_id AS `CategoriesProducts__category_id` FROM products Products INNER JOIN categories_products CategoriesProducts ON (CategoriesProducts.product_id in (4325,3632) AND Products.id = (CategoriesProducts.product_id))
When I print out the array with dd($catIds); , I get an array with _matchingData
array:4 [▼
0 => array:2 [▼
"id" => 3632
"_matchingData" => array:1 [▼
"CategoriesProducts" => array:1 [▼
"category_id" => 10
]
]
]
1 => ...
]
how do i get category_id under id
(i have already checked that thread How to print _matchingData object value in cakephp 3 but still no success)
got it. i need to alias the category_id to prevent nesting
->select(['category_id' => 'CategoriesProducts.category_id'])

Laravel How Make DB raw can inside funtion

I have problem on laravel. I want to showing percentage on with eloquent, but return null value
This Is My Controller
$group_categories = Proyek::with(['modul' => function($query){
$query->select(DB::raw('((select count(*) from modul where status = 0 and deleted_at IS NULL) /
(select count(*) from modul where deleted_at IS NULL)) *
100 as count' ));
}])->get();
This Is Json return
{
id: "10",
proyek: "JuZka",
created_at: "2018-08-12 01:54:04",
updated_at: "2018-09-23 05:49:13",
modul: [ ]
},
You can use code like this:
$all_models = (new Proyek)->count();
$models = (new Proyek)->where('status', 0)->count();
$percentage = $models / $all_models * 100;
$group_categories = Proyek::wheere('modul', $percentage);

How to create JSON array within a JSON array

3 tables in MYSQL
table_product - product_id, product_name
table_variane - variant_id, variant_name
table_product_variants - product_id, variant_id, MRP, SellPrice
I want to create JSON data out of those in Perl for all the products, in this format:
[
{
"ProductID": "1",
"ProductName": "Green Detergent Bar",
"Variants": [
{
"VariantID": "1",
"VariantName": "500GM",
"MRP": "20.00",
"SellPrice": "19.50"
},
{
"VariantID": "2",
"VariantName": "1KG",
"MRP": "40.00",
"SellPrice": "38.00"
}
]
},
{
"ProductID": "2",
"ProductName": "ABCD",
"Variants": [
{
"VariantID": "3",
"VariantName": "1KG",
"MRP": "200.00",
"SellPrice": "190.50"
},
{
"VariantID": "2",
"VariantName": "1KG",
"MRP": "40.00",
"SellPrice": "38.00"
}
]
}
]
This is Perl Code
my $sql_query = ""; //need to fill this.
my $statement = $db_handle->prepare ($sql_query) or die "Couldn't prepare query '$sql_query': $DBI::errstr\n";
$statement->execute() or die "SQL Error: $DBI::errstr\n";
my #loop_data = ();
while (my #data = $statement->fetchrow_array())
{
my %data = //need to fill this too.
push(#loop_data, \%data);
}
my $json_text = to_json(\#loop_data);
print $json_text;
Please help in filling SQL query and while loop.
Its just a blueprint. Any modification in code is also fine.
That you need arrays (not hashes) complicates things a bit.
Option 1
Use two queries, one that finds the products, and one that finds the variants of a product.
my $product_sth = $dbh->prepare("
SELECT product_id,
product_name
FROM table_product
");
my $variant_sth = $dbh->prepare("
SELECT tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product_variants AS tpv
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
WHERE tpv.product_id = ?
");
my #data;
while (my $product_row = $product_sth->fetchrow_hashref()) {
my #variants;
$variant_sth->execute($product_row->{product_id});
while (my $variant_row = $variant_sth->fetchrow_hashref()) {
push #variants, {
VariantID => $variant_row->{variant_id},
VariantName => $variant_row->{variant_name},
MRP => $variant_row->{MRP},
SellPrice => $variant_row->{SellPrice},
};
}
push #data, {
ProductID => $product_row->{product_id},
ProductName => $product_row->{product_name},
Variants => \#variants,
};
}
my $data_json = to_json(\#data);
Option 2
Use an HoA to group the variants of a product when using a single query.
my $sth = $dbh->prepare("
SELECT tp.product_id,
tp.product_name,
tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product AS tp
JOIN table_product_variants AS tpv
ON tp.product_id = tpv.product_id
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
");
my %data;
while (my $row = $sth->fetchrow_hashref()) {
my $product_id = $row->{product_id};
my $product = $data{$product_id} ||= {
ProductID => $row->{product_id},
ProductName => $row->{product_name},
Variants => [],
};
push #{ $product->{Variants} }, {
VariantID => $row->{variant_id},
VariantName => $row->{variant_name},
MRP => $row->{MRP},
SellPrice => $row->{SellPrice},
};
}
my $data_json = to_json([ values(%data) ]);
Option 3
Use sorting to group the variants of a product when using a single query.
my $sth = $dbh->prepare("
SELECT tp.product_id,
tp.product_name,
tv.variant_id,
tv.variant_name,
tvp.MRP,
tvp.SellPrice
FROM table_product AS tp
JOIN table_product_variants AS tpv
ON tp.product_id = tpv.product_id
JOIN table_variant AS tv
ON tpv.variant_id = tv.variant_id
ORDER BY tp.product_id
");
my $last_product_id = 0;
my #data;
while (my $row = $sth->fetchrow_hashref()) {
my $product_id = $row->{product_id};
if ($product_id != $last_product_id) {
$last_product_id = $product_id;
push #data, {
ProductID => $row->{product_id},
ProductName => $row->{product_name},
Variants => [],
};
}
push #{ $data[-1]{Variants} }, {
VariantID => $row->{variant_id},
VariantName => $row->{variant_name},
MRP => $row->{MRP},
SellPrice => $row->{SellPrice},
};
}
my $data_json = to_json(\#data);
It's a little extra work than option 2, but it has the smallest client-side memory footprint (if you didn't have to keep everything in memory).

Insert data with insert_batch

I'm using the following statement to insert data in mysql with codeigniter.
$this->db->insert_batch($table, $query);
$query is generated dynamically can have different number of columns on each array element
and maybe the number of elements may differ on condition
array (
0 => array(
'column1'=>'insert1',
'column2'=>'insert2'
),
1 => array(
'column1'=>'insert1';
'column2'=>'insert2',
'column4'=>'insert4'
)
)
could this cause an error or handles codigniter from deafult?
I'm building up the query as it follows
foreach ($sql_xml as $children) {
$children = $this->xml2array($children);
foreach ($children as $index => $child) {
if ($child != 'feed_id') {
$keys[$index] = $child;
}
}
}
switch (strtolower($this->config[0]->affiliate)) {
case 'case1':
$target_xml = $target_xml->productItems;
break;
case 'case2':
$target_xml = $target_xml;
break;
default :
break;
}
$query = array();
$data = array();
foreach ($target_xml as $feeds) {
$feeds = $this->xml2array($feeds);
$columns = new RecursiveIteratorIterator(new RecursiveArrayIterator($feeds));
foreach ($columns as $index => $column) {
if (array_key_exists($index, $keys)) {
if($column != ''){
$data[$keys[$index]] = $column;
$data['feed_id'] = $this->id;
}
//*TODO //$data['affiliate'] = "'.$this->config[0]->affiliate.'";
}
}
$query[] = $data;
}
if (count($query > 0)) {
foreach ($query as $t){
$this->db->insert($table, $t);
}
}
The array's would need to have the same amount of "columns".
So what I would recommend is the following (setting certain columns to null if no there is no data):
array (
0 => array(
'column1' => 'insert1',
'column2' => 'insert2',
'column3' => null,
'column4' => null
),
1 => array(
'column1' => 'insert1',
'column2' => 'insert2',
'column3' => 'insert3',
'column4' => 'insert4'
)
)
Also, your syntax is invalid and it would cause an error since you are using a ; instead of an , on the first column insert.

How to parse Hypertable data using php

I have inserted data's in Hypertable. But i don't know, how to get particular value from result. My PHP thrift code is :
$GLOBALS['THRIFT_ROOT'] = "/opt/hypertable/0.9.5.6/lib/php";
require_once $GLOBALS['THRIFT_ROOT'].'/ThriftClient.php';
$client = new Hypertable_ThriftClient("localhost", 38080);
$namespace = $client->namespace_open("appuniv");
$query = "select * from category_details limit 1";
$tab = $client->hql_query($namespace, $query);
var_dump($tab);
I'm getting the below result :
object(Hypertable_ThriftGen_HqlResult)#24 (4) { ["results"]=> NULL
["cells"]=> array(2) { [0]=> object(Hypertable_ThriftGen_Cell)#25 (2)
{ ["key"]=> object(Hypertable_ThriftGen_Key)#26 (6) { ["row"]=>
string(32) "077262cc53a1fb1b5f651d31b6bf81ba" ["column_family"]=>
string(8) "category" ["column_qualifier"]=> string(4) "name"
["timestamp"]=> float(1.3419935154984E+18) ["revision"]=>
float(1.3419935154984E+18) ["flag"]=> int(255) } ["value"]=> string(7)
"Medical" } [1]=> object(Hypertable_ThriftGen_Cell)#27 (2) { ["key"]=>
object(Hypertable_ThriftGen_Key)#28 (6) { ["row"]=> string(32)
"077262cc53a1fb1b5f651d31b6bf81ba" ["column_family"]=> string(8)
"category" ["column_qualifier"]=> string(4) "type" ["timestamp"]=>
float(1.3419935154984E+18) ["revision"]=> float(1.3419935154984E+18)
["flag"]=> int(255) } ["value"]=> string(7) "android" } }
["scanner"]=> NULL ["mutator"]=> NULL } 0.9678
May i know how to get the ["value"]=> string(7) "Medical" value from above result.
/**
* Sort result by column family/qualifier
* #param thrift result
*/
private function sort($data)
{
$result = array();
foreach ($data as $cell)
{
$row = $cell->key->row;
if (!isset($result[$row])) {
$result[$row] = new stdClass;
$result[$row]->row = $cell->key->row;
foreach ($this->columns as $col) {
$pos = strpos($col, ':') ;
$qualifier = ($pos) ? substr($col, $pos + 1) : NULL;
$col = !$pos ? $col : substr($col, 0, $pos);
if (!$qualifier)
$result[$row]->{$col} = NULL;
else if ($qualifier[0] != '/')
$result[$row]->{$col}[$qualifier] = NULL;
}
}
$result[$row]->{$cell->key->column_family}[$cell->key->column_qualifier] = $cell->value;
}
return $result;
}