I am new to magento. I just want to frame a query, but i am struggling to do.
My mysql query:
SELECT `main_table`.*, `t1`.*, count(t2.review_id) AS `totalrecord`, SUM(t2.rating) AS `totalrating`, `t2`.* FROM `nbmp_vendor` AS `main_table`
LEFT JOIN `customer_entity` AS `t1` ON main_table.customer_id = t1.entity_id
LEFT JOIN `nbmp_review` AS `t2` ON main_table.customer_id = t2.vendor_id
WHERE ((vendor_status = '1')) AND (t1.group_id = '4') group by main_table.vendor_id
I have tried in magento:
<?php
class Blazedream_TopVendors_Block_Monblock extends Mage_Core_Block_Template {
public function methodblock() {
$myTable = "customer_entity";
$myTable1 = "nbmp_review";
$collection = Mage::getModel('topvendors/topvendors')->getCollection()
->addFieldToFilter(array('vendor_status'), array('1'))
->setOrder('vendor_id','asc');
$collection->getSelect()
->joinLeft(array("t1" => $myTable), "main_table.customer_id = t1.entity_id")
->where("t1.group_id = '4'");
$collection->getSelect()
->columns('count(t2.review_id) AS totalrecord')
->columns('SUM(t2.rating) AS totalrating')
->joinLeft(array("t2" => $myTable1), "main_table.customer_id = t2.vendor_id")
->group("main_table.vendor_id");
echo $collection->getselect(); die;
$ddata = $collection->getData();
$i = 0;
foreach($ddata as $data)
{
$retour[$i]['id'] = $data->getData('vendor_id');
$retour[$i]['name'] = $data->getData('vendor_name');
$retour[$i]['vendor_slug'] = $data->getData('vendor_slug');
// $retour[$i]['rating_avg'] = $vendors[$data->getData('vendor_id')]['rating_avg'];
$retour[$i]['totalrating'] = $data->getData('totalrating');
$retour[$i]['rating_avg'] = $data->getData('totalrating') / $data->getData('totalrecord');
$i++;
}
// Mage::getSingleton('adminhtml/session')->addSuccess('Cool Ca marche !!');
return $retour;
}
}
I am getting only error.
Fatal error: Call to undefined method Blazedream_TopVendors_Model_Mysql4_TopVendors_Collection::group() in magento
Can anyone help me to form this??
Thanks in advance.
Please try following and see if it helps you.
$myTable = "customer_entity";
$myTable1 = "nbmp_review";
$collection = Mage::getModel('topvendors/topvendors')->getCollection()
->addFieldToFilter(array('vendor_status'), array('1'))
->setOrder('vendor_id','asc');
$collection->getSelect()->group('vendor_id'); // TRY THIS LINE OF CODE
$collection->getSelect()
->joinLeft(array("t1" => $myTable), "main_table.customer_id = t1.entity_id")
->where("t1.group_id = '4'");
$collection->getSelect()
->columns('count(t2.review_id) AS totalrecord')
->columns('SUM(t2.rating) AS totalrating')
->joinLeft(array("t2" => $myTable1), "main_table.customer_id = t2.vendor_id");
Related
I'm working on a system that has several server-side datatables but i facing issues with 2 joins when i try to order de columns.
I receive the following message when try to sort the columns:
Query error: Column 'notes' in order clause is ambiguous - Invalid query: SELECT *
FROM `tbl_project`
LEFT JOIN `tbl_client` ON `tbl_project`.`client_id`=`tbl_client`.`client_id`
LEFT JOIN `tbl_account_details` ON `tbl_project`.`created_by` = `tbl_account_details`.`user_id`
LEFT JOIN `tbl_notes` ON `tbl_project`.`notes` = `tbl_notes`.`notes_id`
WHERE `tbl_project`.`client_id` = '100'
ORDER BY `notes` DESC
LIMIT 10
This is the code with my query:
$id = $this->input->post("client_id");
$client_details = get_row('tbl_client', array('client_id' => $id));
$draw = intval($this->input->post("draw"));
$start = intval($this->input->post("start"));
$length = intval($this->input->post("length"));
$order = $this->input->post("order");
$search= $this->input->post("search");
$search = $search['value'];
$col = 0;
$dir = "";
if(!empty($order))
{
foreach($order as $o)
{
$col = $o['column'];
$dir= $o['dir'];
}
}
if($dir != "desc" && $dir != "desc")
{
$dir = "desc";
}
$valid_columns = array(
0=>'project_id',
1=>'client',
2=>'fullname',
3=>'notes',
4=>'origen',
5=>'end_date',
6=>'project_status',
7=>'action',
);
if(!isset($valid_columns[$col]))
{
$order = null;
}
else
{
$order = $valid_columns[$col];
}
if($order !=null)
{
$this->db->order_by($order, $dir);
}
$searchQuery = "";
if($search != ''){
$searchQuery = " (tbl_project.project_id like'%".$search."%' OR tbl_project.end_date like'%".$search."%' OR tbl_project.project_status like'%".$search."%' OR tbl_notes.notes like'%".$search."%' OR tbl_notes.eco like'%".$search."%' OR tbl_account_details.origen like'%".$search."%' OR tbl_client.name like'%".$search."%') ";
}
$this->db->select('*');
$this->db->from('tbl_project');
$this->db->join('tbl_client', 'tbl_project.client_id=tbl_client.client_id','left');
$this->db->join('tbl_account_details', 'tbl_project.created_by = tbl_account_details.user_id','left');
$this->db->join('tbl_notes', 'tbl_project.notes = tbl_notes.notes_id','left');
$this->db->where('tbl_project.client_id', $client_details->client_id);
if($searchQuery != '')
$this->db->where($searchQuery);
$this->db->limit($length,$start);
$cita = $this->db->get()->result();
For some reason the ORDER BY is not set as tbl_notes.notes
Any suggestion on how to fix this?
Thanks in advance
EDIT: i have added more code so there is more visibility of the process
The error occurs, because your column name is not unique, it exists in more than one table.
append the table name of the searched column to your query to make it unique:
for example in this line:
$this->db->order_by('my_table_name.'.$order, $dir);
that would generate something like
ORDER BY `my_table_name.notes` DESC
edit: or in case you have to address columns from several different tables you could change your $valid_columns array:
$valid_columns = array(
0=>'my_table_name1.project_id',
1=>'my_table_name2.client',
2=>'my_table_name2.fullname',
3=>'my_table_name3.notes',
// etc.
);
and maintain the remaining original code.
i have a problem on passing data result to another data request in a controller in codeigniter is there something i'm missing ?
Controller method :
public function index()
{
//sending $data array of variables to view's or to model's
$data = array('header_title' => 'Nova Democracia - Eleições 2019 - Menu');
$data['formData'] = $this->Crud_model->getProvinciaAndLocal($this->session->id_local);
$data['locais'] = $this->Crud_model->getLocaisByIdLocal($formData["id_distrito"]);
$this->load->view("form_menu/form_menu.php", $data);
}
and my model methods :
function getProvinciaAndLocal($id_local){
$query = $this->db->query("SELECT `nome_local`, `nome_provincia`, tb_local.id_distrito
FROM `tb_user`
INNER JOIN `tb_local`
ON tb_user.id_local = tb_local.id_local
INNER JOIN `tb_distrito`
ON tb_local.id_distrito = tb_distrito.id_distrito
INNER JOIN `tb_provincia`
ON tb_distrito.id_provincia = tb_provincia.id_provincia
WHERE tb_user.id_local = '".$id_local."' ");
$row = $query->row();
$obj = array(
'nome_provincia' => $row->nome_provincia,
'nome_local' => $row->nome_local,
'id_distrito' => $row->id_distrito
);
return $obj;
}
function getLocaisByIdLocal($id_distrito){
$query = $this->db->query("SELECT tb_local.id_local, `nome_local`
FROM `tb_user`
INNER JOIN `tb_local`
ON tb_user.id_local = tb_local.id_local
INNER JOIN `tb_distrito`
ON tb_local.id_distrito = tb_distrito.id_distrito
INNER JOIN `tb_provincia`
ON tb_distrito.id_provincia = tb_provincia.id_provincia
WHERE tb_local.id_distrito = '".$id_distrito."' ");
$row = $query->row();
$obj = array(
'id_local' => $row->id_local,
'nome_local' => $row->nome_local,
);
return $obj;
}
Is there something im doing wrong? Because when i use $formData["nome_provincia"] in the view it works well..
Change your controller like this.
public function index()
{
//sending $data array of variables to view's or to model's
$data = array('header_title' => 'Nova Democracia - Eleições 2019 - Menu');
$data['formData'] = $this->Crud_model->getProvinciaAndLocal($this->session->id_local);
$data['locais'] = $this->Crud_model->getLocaisByIdLocal($data['formData']["id_distrito"]); // Notice the change here
$this->load->view("form_menu/form_menu.php", $data);
}
I have a function getCart which has a complicated query that is merged together. I want to select only one array that is $cart['tee_times'] = array(); and place that array in another function. How can I accomplish this?
Here is a snippet of the query I am trying to pull from.
function getCart($id, DBConnection $connection) {
$query = 'SELECT * FROM cart WHERE IDCart=:cart_id LIMIT 1';
$prepared = array(
"cart_id" => $id
);
$results = $connection->fetch($query, $prepared);
$cart = !empty($results) ? $results[0] : null;
if (isset($cart)) {
$cart['IDCustomer'] = isset($cart['IDCustomer']) ? (int)$cart['IDCustomer'] : null;
$cart['IDDestination'] = isset($cart['IDDestination']) ? (int)$cart['IDDestination'] : null;
$cart['total'] = 0;
$cart['tee_times'] = array();
$cart['rooms'] = array();
$cart['cars'] = array();
$query = '
SELECT
a.*,
e. city_name,
f.IDDestination,
((CASE DATE_FORMAT(a.teetime_dt, "%w")
WHEN 0 THEN b.sun
WHEN 1 THEN b.mon
WHEN 2 THEN b.tue
WHEN 3 THEN b.wed
WHEN 4 THEN b.thu
WHEN 5 THEN b.fri
WHEN 6 THEN b.sat
ELSE 0
END) * a.no_rounds * a.no_golfers) price,
c.tax_rate
FROM cart_course_teetimes a
JOIN course_priceplan b
ON b.IDCoursePricePlan = a.IDCoursePricePlan
JOIN course_tax c
ON c.IDCourseTax = a.IDCourseTax
JOIN course d
ON d.IDCourse = b. IDCourse
JOIN vw_cities e
ON e.IDCity = d. IDCity
JOIN destinations_cities f
ON f.IDCity = e.IDCity
WHERE IDCart=:cart_id
';
$results = $connection->fetch($query, $prepared);
foreach ($results as $row) {
$formatted = array(
'IDCartTeetimes' => (int)$row['IDCartTeetimes'],
'IDCoursePricePlan' => (int)$row['IDCoursePricePlan'],
'IDCourseTax' => (int)$row['IDCourseTax'],
'teetime_date' => $row['teetime_dt'],
'num_golfers' => (int)$row['no_golfers'],
'num_rounds' => (int)$row['no_rounds'],
'price' => (float)$row['price'],
'tax_rate' => (float)$row['tax_rate'],
'city_name' => $row['city_name'],
'IDDestination' => (int)$row['IDDestination'],
);
$cart['tee_times'][] = $formatted;
$cart['total'] += $formatted['price'];
}
Here is my function and my attempt at retrieving the tee_times array
function filterCart($cart_id, DBConnection $connection) {
$cart = getCart($cart_id, $connection);
if (!isset($cart)) {
http_response_code(404);
return 'Cart does not exist.';
}
$results =$cart['tee_times'];
echo $results;
$id = null;
foreach ($results as $row){
var_dump($row['IDDestination']);
If you want to filter out courses that have more than one IDDestination, change the WHERE clause to:
WHERE IDCart = :cart_id
AND IDCart NOT IN (
SELECT IDCart
FROM course a
JOIN destinations_cities b ON b.IDCity = a.IDCity
GROUP BY IDCart
HAVING COUNT(*) > 1)
I am a student who learns CodeIgniter, I have a school assignment about the database, I create a project, and run query in my model just like this.
class Send_model extends CI_Model{
function hello(){ $table = $this->db->query("SELECT * FROM (`tbl1`) LEFT JOIN `tbl2` ON `tbl2`.`id` = `tbl1`.`child_id` LEFT JOIN `tbl3` ON `tbl3`.`id` = `tbl1`.`child_id` ");
foreach($table->result() as $row){
$modbus[]= $row->modbus;
$data []= $row->data;
$alert[]= $row->alert;
};
$param0 = '&'.$modbus[0].'='.$data[0].':'.$alert[0];
$param1 = '&'.$modbus[1].'='.$data[1].':'.$alert[1];
$param2 = '&'.$modbus[2].'='.$data[2].':'.$alert[2];
$param3 = '&'.$modbus[3].'='.$data[3].':'.$alert[3];
$param4 = '&'.$modbus[4].'='.$data[4].':'.$alert[4];
$param5 = '&'.$modbus[5].'='.$data[5].':'.$alert[5];
$param6 = '&'.$modbus[6].'='.$data[6].':'.$alert[6];
$param7 = '&'.$modbus[7].'='.$data[7].':'.$alert[7];
$param8 = '&'.$modbus[8].'='.$data[8].':'.$alert[8];
$param9 = '&'.$modbus[9].'='.$data[9].':'.$alert[9];
$param10 = '&'.$modbus[10].'='.$data[10].':'.$alert[10];
$param11= '&'.$modbus[11].'='.$data[11].':'.$alert[11];
$param12 = '&'.$modbus[12].'='.$data[12].':'.$alert[12];
$param13 = '&'.$modbus[13].'='.$data[13].':'.$alert[13];
$param14 = '&'.$modbus[14].'='.$data[14].':'.$alert[14];
$param15 = '&'.$modbus[15].'='.$data[15].':'.$alert[15];
$param16 = '&'.$modbus[16].'='.$data[16].':'.$alert[16];
$param17 = '&'.$modbus[17].'='.$data[17].':'.$alert[17];
$param18 = '&'.$modbus[18].'='.$data[18].':'.$alert[18];
$sent = $param0.$param1.$param3.$param4.$param5.$param6.$param7.$param8.$param9.$param10.$param11.$param12.$param13.$param13.$param14.$param15.$param16.$param17;
return $sent;
}
my controller just like this
class Send extend CI_Controller{
function data ()
{
$this->load->model('send_model');
$send = $this->model->send_model->hello();
echo $sent;
}
}
i have a problem,if tbl1 add data then i have to write adding code to my script
can anyone help me to simplify this code?
It is because you're hard-coding to send only 19 rows of data by creating 19 $param variables. In a dynamic condition, you may have an empty record-set or hundreds of records. Modify the structure of your foreach loop to the following:
$param = array();
foreach($table->result() as $row){
$param[] = '&'.$row->modbus.'='.$row->data.':'.$row->alert;
}
return $param;
Hope it answers your question.
I use Yii, and I get this error; What should I understand and do?
Not a duplicate of: source or any other;
error is at: ->bindParam(":url_id", $url->id)
$url = Url::model()->findByAttributes(array('link' => $_url));
if (empty($url)) {
$url = new Url();
$url->website_id = $website->id;
$url->link = $_url;
$url->title = '';
$url->description = '';
$url->doctype = $_doctype;
$url->visits = 1;
$url->created = date('Y-m-d h:i:s',time());
$url->updated = date('Y-m-d h:i:s',time());
$url->status = 1;
$url->save(false);
} else {
// update visits
$url->saveCounters(array('visits' => 1));
// url existed, let's load products
if (!Yii::app()->user->isGuest) {
$sql = "select u.id from url as u
left join url_follower as u_f
on u.id = u_f.url_id and u_f.user_id = :user_id
where u.id =:url_id";
$cmd = Yii::app()->db->createCommand($sql)
->bindParam(":url_id", $url->id)
->bindParam(":user_id", Yii::app()->user->id);
$url_id = $cmd->queryScalar();
The solution, tested:
$user_id = Yii::app()->user->id;
$url_id = $url->id;
$cmd = Yii::app()->db->createCommand($sql)
->bindParam(":user_id", $user_id)
->bindParam(":url_id", $url_id);