Why sphinx does not return attributes name? - sphinx

I use two indexes for search in Sphinx:
#users
source users : lsParentSource
{
sql_query_range = SELECT MIN(idDetailToUsers), MAX(idDetailToUsers) FROM detailtousers
sql_query = SELECT idDetailToUsers as id, 1000 as type, UsersTypeAccount, idDetailToUsers, SpecializationName, DetailToUsersName, DetailToUsersPhoto, city, country FROM detailtousers join users ON users.idUsers = detailtousers.idDetailToUsers left join usersspecialization ON usersspecialization.UsersSpecializationIdUser = detailtousers.idDetailToUsers left join specializationtousers ON specializationtousers.idSpecialization = usersspecialization.UsersSpecializationIdSpecialization WHERE idDetailToUsers >= $start AND idDetailToUsers <= $end GROUP BY idDetailToUsers
sql_attr_uint = type
sql_attr_uint = idDetailToUsers
sql_attr_uint = UsersTypeAccount
sql_field_string = SpecializationName
sql_field_string = DetailToUsersName
sql_field_string = DetailToUsersPhoto
sql_attr_uint = city
sql_attr_uint = country
sql_query_info = SELECT idDetailToUsers, DetailToUsersName, UsersTypeAccount, SpecializationName, DetailToUsersPhoto, city, country \
FROM detailtousers WHERE idDetailToUsers = $id
sql_ranged_throttle = 0
}
#medical
source medical : lsParentSource
{
sql_query_range = SELECT MIN(idMedicalFacilities), MAX(idMedicalFacilities) FROM medicalfacilities
sql_query = SELECT idMedicalFacilities as id, 2000 as type, idMedicalFacilities, MedicalFacilitiesName, MedicalFacilitiesPhoto, city, country FROM medicalfacilities WHERE idMedicalFacilities >= $start AND idMedicalFacilities <= $end
sql_attr_uint = type
sql_attr_uint = MedicalFacilitiesIdUser
sql_attr_uint = idMedicalFacilities
sql_field_string = MedicalFacilitiesName
sql_field_string = MedicalFacilitiesPhoto
sql_attr_uint = city
sql_attr_uint = country
sql_query_info = SELECT MedicalFacilitiesIdUser, MedicalFacilitiesName, MedicalFacilitiesPhoto FROM medicalfacilities WHERE idMedicalFacilities = $id
sql_ranged_throttle = 0
}
If use an index users only it returns me all attributes specified in select query.
But if use a two indexes the sphinx does not return attributes.
What is reason?
Result for index users:
array(1) {
[533]=>
array(2) {
["weight"]=>
int(1)
["attrs"]=>
array(0) {
}
}
}
Result for index medical:
array(5) {
[451]=>
array(2) {
["weight"]=>
int(2)
["attrs"]=>
array(0) {
}
}
[444]=>
array(2) {
["weight"]=>
int(1)
["attrs"]=>
array(0) {
}
}

Sphinx only returns attributes common to the indexes in the query. you have different names.
You might be able to use the EXISTS function from sphinxQL in the SetSelect, but never tried.
Easiest is just to use the same attribute names.

Related

I want to get product list with category and category listed as in two different columns in woocommerce

i want to get product list with parent category and subcategory as seperate in the result in woocommerce
This code I have tried
SELECT
p.ID,
p.post_title,
`post_content`,
`post_excerpt`,
t.name AS product_category,
t.term_id AS product_id,
t.slug AS product_slug,
tt.term_taxonomy_id AS tt_term_taxonomia,
tr.term_taxonomy_id AS tr_term_taxonomia,
MAX(CASE WHEN pm1.meta_key = '_price' then pm1.meta_value ELSE NULL END) as price,
MAX(CASE WHEN pm1.meta_key = '_regular_price' then pm1.meta_value ELSE NULL END) as
regular_price,
MAX(CASE WHEN pm1.meta_key = '_sale_price' then pm1.meta_value ELSE NULL END) as sale_price,
MAX(CASE WHEN pm1.meta_key = '_sku' then pm1.meta_value ELSE NULL END) as sku
FROM wp_posts p
LEFT JOIN wp_postmeta pm1 ON pm1.post_id = p.ID
LEFT JOIN wp_term_relationships AS tr ON tr.object_id = p.ID
JOIN wp_term_taxonomy AS tt ON tt.taxonomy = 'product_cat' AND tt.term_taxonomy_id =
tr.term_taxonomy_id
JOIN wp_terms AS t ON t.term_id = tt.term_id
WHERE p.post_type in('product', 'product_variation') AND p.post_status = 'publish' AND
p.post_content <> ''
GROUP BY p.ID,p.post_title
Any Idea,thanks in advance
If you want to get a list of products with parent_category and sub_category in an array format, then you can use WordPress WP_Query. Try following code snippet.
<?php
// fetch all products from woocommerce
$args = array('post_type' => 'product', 'posts_per_page' => -1);
$loop = new WP_Query($args);
$product_list_array = []; // result array with product_id,parent_category and sub_category
while ($loop->have_posts()) : $loop->the_post();
global $product;
$product_id = $product->get_id();
$result = []; $parent_cats = []; $sub_cats = [];
$result['product_id'] = $product_id;
$categories = get_the_terms($product_id, 'product_cat'); // get category list of a product
foreach ($categories as $category) {
// check if it is a parent or child
if ($category->parent == 0) {
$parent_cats[] = $category->name;
} else {
$parent_cat = get_term_by('id', $category->parent, 'product_cat'); // to get parent category name
$sub_cats[] = $category->name;
$parent_cats[] = $parent_cat->name;
}
}
// if multiple category exist then join them to a string
$result['parent_category'] = implode(" | ", array_unique($parent_cats));
$result['sub_category'] = implode(" | ", array_unique($sub_cats));
$product_list_array[] = $result;
endwhile;
?>
The $product_list_array should contain product_id,parent_category and sub_category.

How can i get rank or position base highest ' gpa' and 'total' into database rows data in codeigniter?

How can i get rank or position base highest ' gpa' and 'total' into database rows data in codeigniter?
public function fetchData() {
$data = array();
$data['fetch_data'] = $this->excel_data_insert_model->fetch_data();
$result = $data['fetch_data']->result();
foreach ($result as $row) {
//echo $row.'<br/>';
$id = $row->id;
$p_student_id = $row->stu_id;
$p_section = $row->section;
$p_gpa = $row->gpa;
$p_total = $row->total;
$x = 0;
}
}
My Answer to your raw query could be this:
Select column_name1, column_name2, MAX(gpa),MAX(total) from tbl_v1 ORDER by gpa, total desc
Also for CI
$query=$this->db->select('column_name1, column_name2, MAX(gpa),MAX(total)')->order_by('gpa,total','desc'‌​)->get('tbl_v1');
return $query;

sphinx autocomplete CALL SNIPPETS excerpts not returning result set

i am able to get a result set from print_r($stmt->fetchAll()); however, i cannot get a result set from print_r($r); below is the exact code from https://github.com/adriannuta/SphinxAutocompleteExample. the only change is the sql_query inside the sphinx.conf file.
ajax_suggest_excerpts.php
require_once 'common.php';
require_once 'functions.php';
$indexes = 'simplecomplete';
$arr =array();
$q = trim($_GET['term']);
$stmt = $ln_sph->prepare("SELECT * FROM $indexes WHERE MATCH(:match) LIMIT 0,10 OPTION ranker=sph04");
$aq = explode(' ',$q);
if(strlen($aq[count($aq)-1])<3){
$query = $q;
}else{
$query = $q.'*';
}
$stmt->bindValue(':match', $query,PDO::PARAM_STR);
$stmt->execute();
$docs = array();
$title = "";
$stmsnp = $ln_sph->prepare("CALL SNIPPETS(:doc,'simplecomplete',:query)");
$stmsnp->bindValue(':query',$query,PDO::PARAM_STR);
$stmsnp->bindParam(':doc',$title,PDO::PARAM_STR);
print_r($stmt->fetchAll()); //THIS RETURNS RESULT SET
foreach($stmt->fetchAll() as $r){
$title = $r['city'];
$stmsnp->execute();
$r = $stmsnp->fetch();
print_r($r); //THIS DOES NOT.
$arr[] = array('id' => utf8_encode($r['city']),'label' =>utf8_encode( $r['city']));
}
echo json_encode($arr);
exit();
sphinx.conf
source simplecomplete
{
type = mysql
sql_host = localhost
sql_user = swflorib
sql_pass = cii65419
sql_db = swflorib_db
sql_port = 3306 # optional, default is 3306
sql_query = SELECT id, Sic_Code_description, Sic_Code6_Description, City, hidden_keywords FROM no_admin_emails GROUP BY Company_Name
sql_field_string = Sic_Code_description
sql_field_string = Sic_Code6_Description
sql_field_string = City
sql_field_string = hidden_keywords
}
index simplecomplete
{
source = simplecomplete
path = /usr/local/sphinx/var/data/simplecomplete
docinfo = extern
charset_type = utf-8
min_word_len = 3
enable_star = 1
min_prefix_len = 3
}
From the documentation of fetchAll
http://us3.php.net/manual/en/pdostatement.fetchall.php
returns an array containing all of the remaining rows in the result set.
So the fetchAll inside the print_r() fetches all the rows from the database. The fetchAll inside the foreach() then has no rows left to fetch!
Looks like a misunderstanding of PHP/pdo.

Querying for dates in doctrine

I have a table called active_plans in which there are two columns: activated_date and last_billed_at. Basically, I want to create a query that looks at these two columns like this:
select all from active_plans
where last_billed_at = null AND activated_date + 1 month = today,
or if last_billed_at + 1 month = today.
I can't seem to figure out how to do this, though.
I wound up doing something a lot different:
public function getBillToday()
{
$activePlans = $this->entityManager
->createQuery('SELECT adp FROM adp
WHERE adp.activationDate IS NOT NULL')
->getResult();
$data = array();
foreach ($activePlans as $plan) {
$recur = $plan->getPlan()->getRecurringInMonths();
$nextBillTime = strtotime('-'.$recur.' months', time());
$nextBill = date('Y-m-d', $nextBillTime);
$activationDate = $plan->getActivationDate();
$lastBilledAt = $plan->getLastBilledAt() != NULL ? $plan->getLastBilledAt()->format('Y-m-d') : 0;
if ($activationDate == $nextBill || $lastBilledAt == $nextBill) {
$data[] = $plan->getId();
}
}
return $data;
}

How do I do this sql query in Zend?

How do I do this sql query in Zend Framework, I need to some how do this in the PDO context I think? I tried ->query but not sure if I am getting this right. The three variables are user_id and to and from date.
SELECT
ss.subcategory_id,
ss.subcategory_name,
ss.subcategory_issaving,
IFNULL(SUM(m.mv_monthly_total),0) AS expendsum
FROM
(SELECT
s.subcategory_id,
s.subcategory_name,
s.subcategory_issaving
FROM
subcategory s
WHERE
s.subcategory_isexpend = 'Y'
AND
s.subcategory_issaving = 'Y') ss
LEFT JOIN
mv_monthly m
ON ss.subcategory_id = m.mv_monthly_subcategory_id
AND m.mv_monthly_user_id = 2
AND m.mv_monthly_month >= '2010-01-01'
AND m.mv_monthly_month <= '2020-01-01'
GROUP BY
ss.subcategory_id,
ss.subcategory_name,
ss.subcategory_issaving
ORDER BY
ss.subcategory_issaving DESC,
expendsum;
I have tried the following with no luck
$db = Zend_Db_Table::getDefaultAdapter();
$dbExpr1 = new Zend_Db_Expr("s.subcategory_id, s.subcategory_name, s.subcategory_issaving");
$dbExpr2 = new Zend_Db_Expr("ss.subcategory_id, ss.subcategory_name, ss.subcategory_issaving, IFNULL(SUM(m.mv_monthly_total),0) AS expendsum");
$select = $db->select()
->from(
array(
'ss' => new Zend_Db_Expr(
'('. $db->select()
->from(array("s" => "subcategory"), $dbExpr1)
->where("s.subcategory_isexpend = 'Y'")
->where("s.subcategory_issaving = 'Y'") .')'
)
),
$dbExpr2
)
->joinLeft(array("m" => "mv_monthly"), "ss.subcategory_id = m.mv_monthly_subcategory_id")
->where("m.mv_monthly_user_id = ?", $user_id)
->where("m.mv_monthly_month >= ?", $fromMonth)
->where("m.mv_monthly_month <= ?", $toMonth)
->group(array("ss.subcategory_id","ss.subcategory_name","ss.subcategory_issaving"))
->order(array("ss.subcategory_issaving DESC", "expendsum"));
$row = $db->fetchAll($select);
For such a complex query, you can just execute it directly rather than using the object oriented approach as it gets fairly complicated with a query like that.
Try something like this, replacing my query with yours, and binding your variables into the query:
$db = Zend_Db_Table::getDefaultAdapter();
$stmt = new Zend_Db_Statement_Pdo($db, 'SELECT a, b, c FROM a WHERE username = ? AND date = ?');
try {
$res = $stmt->execute(array($user_id, $fromMonth));
if ($res) {
$rows = $stmt->fetchAll();
}
} catch (Zend_Db_Statement_Exception $dbex) {
// log Query failed with exception $dbex->getMessage();
}
If you prefer to use the object oriented approach, or need to because some parts of the query will be conditional, I usually build by subqueries up first as their own select, and you can simply embed those in to the main query with the select object for the subquery.
Here is what I mean by that:
$subselect = $this->getDbTable()
->select()
->from('mytable', array('time' => 'max(time)', 'id'))
->where('id IN (?)', $serialNumbers)
->group('id');
$select = $this->getDbTable()
->select()
->setIntegrityCheck(false)
->from('mytable')
->join('other', 'mytable.id = other.id', array('label'))
->join(array('dt' => $subselect),
'(mytable.time, mytable.id) = (dt.time, dt.id)', '');