Column not found: 1054 Unknown column '2' in 'on clause' - InnerJoin query not working properly - sql

I am trying to execute the following code, the error applies to the $waitingToBeShipped... section of the code. As you can see I am using an innerJoin. I want to retrieve all of the rows that have orders containing products that are still waiting to be shipped.
public function destroyMany($ids) {
$status = false;
$ids = explode(",", $ids);
foreach ($ids as $id) {
$innerJoin = OrderDetails::where('product_id', $id)->pluck('order_id');
if ($innerJoin->count()) {
$innerJoin = preg_replace("/[^A-Za-z0-9\-]/", '', $innerJoin);
Log::info($innerJoin);
}
$waitingToBeShipped = Order::where('is_delivered', 0)
->join('order_details', 'orders.id', '=', $innerJoin)
->get();
}
}
But it returns:
local.ERROR: SQLSTATE[42S22]: Column not found: 1054 Unknown column '2' in 'on clause' (SQL: select * from `orders` inner join `order_details` on `orders`.`id` = `2` where `is_delivered` = 0 and `orders`.`deleted_at` is null)
I've tried to run this query manually in PHPMyAdmin, which also gives an error with the literal query that I just copied, BUT, when I remove the backticks around the number 2, it does actually give me a result.
I am not sure how I can do the same for my code? Any help would be appreciated, thanks!

The fix to this is to change the query to:
public function destroyMany($ids) {
$status = false;
$ids = explode(",", $ids);
foreach ($ids as $id) {
$innerJoin = OrderDetails::where('product_id', $id)->pluck('order_id');
if ($innerJoin->count()) {
$innerJoin = preg_replace("/[^A-Za-z0-9\-]/", '', $innerJoin);
Log::info($innerJoin);
}
$waitingToBeShipped = Order::where('is_delivered', 0)
->join('order_details', 'orders.id', '=', 'order_details.order_id')
->where('order_details.order_id', $innerJoin)
->get();
}
}

Related

Selecting data from 3 tables in database in Codeigniter

I want to collect values from 3 tables in a database. I have used following code;
public function view_event( $where=array())
{
$this->db->select('client.name, client.contact,event.eid, event.hall, event.event_date,
event.time, event.guests, payment.Paid');
$this->db->where($where);
$this->db->from('client', 'event');
$this->db->join('event', 'event.client_id = client.id');
$this->db->join('payment', 'payment.event_id = event.eid');
$result = $this->db->get();
return $result->result();
}
But this code gives following error;
Error Number: 1054
Unknown column 'payment.Paid' in 'field list'
Use this :
public function view_event( $where=array())
{
$this->db->select('client.name,
client.contact,event.eid,event.hall,event.event_date, event.time,
event.guests,
payment.Paid')
->from('client')
->join('event', 'event.client_id = client.id', 'LEFT')
->join('payment', 'payment.event_id = event.eid', 'LEFT')
return $this->db->get()->result();
}

Query giving double result instead of single

I have two tables: products and current_product_attribute_values
I have tried a join query to filter them as per attribute selected by the user but when I try this with an additional condition it gives me 2 results instead of one it is including the first one which is not matching as per query:
select * from `products` inner join `current_product_attribute_values` on `products`.`id` = `current_product_attribute_values`.`product_id` where `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `product_name` LIKE ?
here is my laravel Controller code :
$all = Input::all();
$q = Input::get('search_text');
$att_val = Input::get('attribute_value');
$subcat = Input::get('subcat_id');
$subcat_name = DB::table('subcategories')->where('id', $subcat)->value('subcategory_name');
$brandname = DB::table('brands')->where('subcat_id', $subcat)->value('brand_name');
$brand_id = DB::table('brands')->where('subcat_id', $subcat)->value('id');
$product_count = DB::table('products')->where('brand_id', $brand_id)->count();
if ($q != "") {
// getting multiple same name params
$query = DB::table('products');
$query->join('current_product_attribute_values', 'products.id', '=', 'current_product_attribute_values.product_id');
$j = 0;
foreach ($all as $key => $values) {
//echo 'my current get key is : ' . urldecode($key). '<br>';
if ($key == $name[$j]) {
$query->where('current_product_attribute_values.attribute_id', '=', $att_id_value[$j]);
echo'<br>';
print_r($query->toSql());
echo'<br>';
//echo '<br> key matched and have some value : <br>';
//echo count($values);
if (count($values) >= 1) {
//echo '<br> it has array inside <br>';
foreach ($values as $val) {
// or waali query in same attribute
echo'<br>';
$query->orwhere('current_product_attribute_values.attribute_value_id', '=', $val);
print_r($query->toSql());
echo'<br>';
}
}
$j++;
}
}
$records = $query->toSql();
$query->where('product_name', 'LIKE', '%' . $q . '%');
$records = $query->toSql();
print_r($records);
$products = $query->paginate(10)->setPath('');
$pagination = $products->appends(array(
'q' => Input::get('q')
));
if (count($products) > 0) {
$filters = DB::table('product_attributes')->where('subcategory_id', $subcat)->get(['attribute_title']);
} else {
$filters = array();
}
$categories = categories::where('add_to_menu', 1)->with('subcategories')->with('brands')->get();
$categoryhome = categories::where('add_to_menu', 1)->with('subcategories')->get();
return view('searchfilter')
->with('productsdata', $products)
->with('filtersdata', $filters)
->with('categories', $categories)
->with('categorieshome', $categoryhome)
->with('subcat_name', $subcat_name)
->with('subcat_id', $subcat)
->with('brandname', $brandname)
->with('product_count', $product_count)
->with('querytext', $q);
}
return 'No Details found. Try to search again !';
its easier if you use raw sql as calling db select function. ex:
$query=DB::select("select * from `products` inner join `current_product_attribute_values` on `products`.`id` = `current_product_attribute_values`.`product_id` where `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `current_product_attribute_values`.`attribute_id` = ? or `current_product_attribute_values`.`attribute_value_id` = ? and `product_name` LIKE ?
");
indeed you can concat vars in raw sql if you need to, ex:
$queryBrands = "select id from brands where subcat_id =".$subcat;
//echo $queryBrands
$queryBrands = DB::select($queryBrands);
By looking at your tables, product table with id value 17 has two records in table current_product_attribute_values in column product_id (I assume this column is used as foreign key to product table).
With select *, you select all of the columns from both tables. So it would most likely cause your query to return multiple records.
My suggestions:
Only select the columns you need. Avoid using select * in the long run, i.e. select product.id, product.description, current_product_attribute_values.attribute_values ......
Make use of GROUP BY
Hope these helps.

How to select data from table that not inserted on other table in codeigniter

I've two tables products, stock I want to select all rows from table products that not inserted on stock and i've 2 conditions
1: column products.s_compnay_id = users.u_company_id
2: cloumn stock.s_company_id =users.u_company_id
that's my model
<?php
Class UserProducts_m extends CI_Model{
function index(){
$session_data = $this->session->userdata('logged_in');
$name = $session_data['username'];
$this->db->select('u_company_id');
$this->db->from('users');
$this->db->where('u_username', $name);
$user_data = $query = $this->db->get();
if ($user_data->num_rows() > 0) {
foreach ($query->result_array() as $row_userdata) {
$usercompanyid[] = $row_userdata;
}
$usercompany=$usercompanyid[0]['u_company_id'];
}
$query="select products.* from products where !FIND_IN_SET(products.p_id,select stock.s_p_id from stock and stock.s_company_id=$usercompany and p_company_id=$usercompany)";
$this->db->query($query);
$result= $this->db->get();
if ($result->num_rows() > 0) {
foreach ($result->result_array() as $row_result) {
$product_data[] = $row_result;
}
}
//return $result=$query->result();
}
}
?>
And that's my controller
<?php
Class UserProducts extends CI_Controller {
function index(){
$this->load->model("UserProducts_m");
$this->load->model("user");
$this->load->view("userproducts_v",array(
'userdata'=>$this->user->userdata(),
'userproducts'=>$this->UserProducts_m->index()
));
}
}
?>
that's my errors
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'select stock.s_p_id from stock and stock.s_company_id=1 and p_company_id=1)' at line 1
select products.* from products where !FIND_IN_SET(products.p_id,select stock.s_p_id from stock and stock.s_company_id=1 and p_company_id=1)
Filename: C:/xampp/htdocs/Elvan/system/database/DB_driver.php
Line Number: 691
I suggest you try putting curly braces around the vars in your query statement. Then it should resolve to array values properly.
$query="select products.* from products where
!find_in_set(products.p_id,select stock.s_p_id from stock and
stock.s_company_id = {$usercompanyid[0]['u_company_id']} and
p_company_id = {$usercompanyid[0]['u_company_id']})";
I see a couple other problems.
The line
$result= $this->db->get();
is not needed because $this->db->query($query); already returned a database result object. Do this
$result = $this->db->query($query);
if ($result->num_rows() > 0)
{ ...
Then you have this useless block of code (Pardon me for being blunt)
foreach ($result->result_array() as $row_result)
{
$product_data[] = $row_result;
}
This is useless because your code just copies array values from one array to another. You'll save a lot of code execution with the following which produces the same thing your foreach loop does.
$product_data = $result->result_array();
result->array() returns an array where each item is an array representing a table row.
You did the same thing earlier adding items to the $usercompanyid array. Do this.
if ($user_data->num_rows() > 0)
{
$usercompanyid = $query->result_array();
}
One last problem. It appears that UserProducts_m::index() does not return anything.
You can use the NOT IN sql query for this.
SELECT *
FROM products
WHERE product_id NOT IN (select field name form stock where clause);

I get Error in laravel query when i use count(rating) as productRating then it not found productRating Field

I join My product table to review table then i count the rating of product then put condityion on rating then i got error that field not found.
Code:
$products = Product::leftjoin('reviews','products.id','=','reviews.productID')
->select('products.*',DB::raw("AVG(rating) as 'productRating'"))
->where('products.status','=',"enable")
->where(function($query) use ($categoriesID,$brands,$priceArray,$ratingArray)
{
$query->whereIn('categoryID',$categoriesID);
if(count($brands) > 0)
{
$query->whereIn('brandID',$brands);
}
$query->whereBetween('productSellingPrice',$priceArray);
if(count($ratingArray) > 0)
{
$query->whereBetween('productRating',$ratingArray);
}
})
->groupBy('products.id')
->get();
Error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'productRating' in 'where clause' (SQL: select `products`.*, AVG(rating) as 'productRating' from `products` left join `reviews` on `products`.`id` = `reviews`.`productID` where `products`.`status` = enable and (`categoryID` in (1, 3, 4, 8, 9, 11, 18, 21, 28, 31) and `productSellingPrice` between 50 and 5000 and `productRating` between 4 and 5) group by `products`.`id`)
This is SQL, not laravel, error.
You can not use aggregated field is where clause, you need to use having instead.
$products = Product::leftjoin('reviews','products.id','=','reviews.productID')
->select('products.*',DB::raw("AVG(rating) as 'productRating'"))
->where('products.status','=',"enable")
->whereIn('categoryID',$categoriesID)
->whereBetween('productSellingPrice',$priceArray)
->groupBy('products.id');
if(count($brands) > 0)
{
$products->whereIn('brandID',$brands);
}
if(count($ratingArray) > 0)
{
// assume $ratingArray = [$min, $max];
list($ratingMin, $ratingMax) = $ratingArray;
$products->having('productRating', '>', $ratingMin);
$products->having('productRating', '<', $ratingMax);
}
$items = $products->get();
thank you Everyone i already solved it
Code:
$products = Product::leftjoin('reviews','products.id','=','reviews.productID')
->select('products.*',DB::raw("IFNULL(AVG(rating),0) as 'productRating'"))
->where('products.status','=',"enable")
->where(function($query) use ($categoriesID,$brands,$priceArray)
{
$query->whereIn('categoryID',$categoriesID);
if(count($brands) > 0)
{
$query->whereIn('brandID',$brands);
}
$query->whereBetween('productSellingPrice',$priceArray);
})
->groupBy('products.id')
->having('productRating', '>=', $startRating)
->having('productRating', '<=', $endRating)
->get();

Conditions in JOINed tables shows error CakePHP

I have two tables employee_personals where all the personal record of the employee is stored and telephone_bills where the telephone bills paid to a particular employee is stored for each month. Now in my employeePersonalsController.php I have a function called api_show_employees() which is similar to below :
function api_show_employees() {
//$this->autoRender = false;
//Configure::write("debug",0);
$office_id = '';
$cond = '';
if(isset($_GET['office_id']) && trim($_GET['office_id']) != '') {
$office_id = $_GET['office_id'];
$cond['EmployeePersonal.office_id'] = $office_id;
}
if(isset($_GET['telephoneBillTo']) && isset($_GET['telephoneBillFrom']) ) {
if($_GET['telephoneBillTo'] != '' && $_GET['telephoneBillFrom'] != '') {
$cond['TelephoneBill.bill_from'] = $_GET['telephoneBillFrom'];
$cond['TelephoneBill.bill_to'] = $_GET['telephoneBillTo'];
}
}
$order = 'EmployeePersonal.name';
// $employee = $this->EmployeePersonal->find('all');
$employee = $this->EmployeePersonal->find('all',array('order' => $order,'conditions'=>$cond));
//return json_encode($employee);
}
This functions basically finds all the employees who paid bills in the given period. But I am getting an error
Error: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'TelephoneBill.bill_from' in 'where clause'
Models : EmployeePersonal.php:
var $hasMany = array(
'TelephoneBill' => array(
'className' => 'TelephoneBill',
)
);
TelephoneBill.php
public $name = 'TelephoneBill';
var $hasMany = array('EmployeePersonal');
NB: If I skip the bill_from and bill_to conditions, I am getting the results , with TelephoneBill array !
TLDR: use Joins instead.
Details/Notes:
1) it looks like you're using recursive. Don't do that. Use Containable instead.
2) You can't limit the parent model based on conditions against data from a contained/recursive-included table - instead, use Joins.
2b) Or, you could query from the other direction, and query your TelephoneBill with conditions, then contain the EmployeePersonal.