order by clause in codeigniter - codeigniter

I want to fetch the database data by descending order of posted date.Database containing a field named as posted_date. This is my code(in model) for fetch the data.
public function get_data_by_volunteer_id($fields = "*", $volunteer_id)
{
$this->db->select($fields);
$query = $this->db->get_where(self::$tbl_name, array(
"user_id" => $volunteer_id));
return( $query->result() );
}

You can try this
function get_data_by_volunteer_id($fields, $volunteer_id)
{
$query = $this->db->query("SELECT * FROM table_name WHERE user_id = '$volunteer_id' ORDER BY posted_date DESC");
$result = $query->result_array();
return $result;
}

Add following in your query
$this->order_by('posted_date', 'desc');
So your final query would be
$this->db->select($fields);
$this->db->get_where(self::$tbl_name, array(
"user_id" => $volunteer_id));
$this->order_by('posted_date', 'desc');
$query=$this->db->get();
return $query->result();

Related

How to do join table by ID as primary key in query -laravel

I want to do a function where filter based on 2 database tables. However, Im not sure how to put the join table in the query. Which means the data will be filtered from two table (user and employee tables) before returning the result to the datatable.
My filter query is
public function filterQuery(Request $request){
$age = $request->age;
$gender= $request->gender;
$query = user::query();
if(!empty($request->age)){
$query->where('age','>=',$age );
}
if(!empty($request->gender)){
$query->where('gender','<=',$gender);
}
$data = $query->get();
return datatables()->of($data)->make(true);
}
The table that I want to join in the query is from table employee (column = income and house_ownership) .and the primary key that connect both tables is IC.
If you have relationship in both model, you can use whereHas:
if(!empty($request->income) || !empty($request->house_ownership)){
$query->whereHas('employee', function($q) use ($income, house_ownership) {
if (!empty($income)) {
$q->where('income', $income);
}
if (!empty($house_ownership)) {
$q->where('house_ownership', $house_ownership);
}
});
}
...
Or you can just use join or leftjoin to filter another table:
public function filterQuery(Request $request){
$age = $request->age;
$gender= $request->gender;
$house_ownership = $request->house_ownership;
$income= $request->income;
$query = user::query();
$query->leftjoin('employee', 'employee.IC', '=', 'user.IC');
if(!empty($request->age)){
$query->where('user.age','>=',$age );
}
if(!empty($request->gender)){
$query->where('user.gender','<=',$gender);
}
if(!empty($request->income)){
$query->where('employee.income', $income);
}
if(!empty($request->house_ownership)){
$query->where('employee.house_ownership', $house_ownership);
}
$data = $query->select('user.*')->get();
return datatables()->of($data)->make(true);
}
Try This
public function filterQuery(Request $request){
$age = $request->age;
$gender= $request->gender;
if(!empty($request->age)){
$data = User::where('age','>=',$age)->get();
}
if(!empty($request->gender)){
$data = User::where('gender','<=',$gender)->get();
}
return datatables()->of($data)->make(true);
}
You can use Eloquent::when() to reduce if-else for Conditional Queries.
public function filterQuery(Request $request){
$query = user::query();
$query->select('user.*')->join('employee', 'employee.IC', '=', 'user.IC');
$data = $query
->when(request('age') != null , function ($q) {
return $query->where('user.age','>=',request('age'));
})
->when(request('gender') != null , function ($q) {
return $query->where('user.gender','<=',request('gender'));
})
->when(request('income') != null , function ($q) {
return $query->where('employee.income','<=',request('income'));
})
->when(request('house_ownership') != null , function ($q) {
return $query->where('employee.house_ownership','<=',request('house_ownership'));
})
->get();
return datatables()->of($data)->make(true);
}

Laravel Database Query Builder error with table name

I'm making a "simple" api for laravel. This api has to handle with filters, pagination and sorting the result. To make this I use laravel query builder. The problem is that it's making a select without a table name, for example:
select * order by `id` asc
My code:
public function index()
{
$request = request();
$query = DB::table('customers')->newQuery();
// Orden
if (request()->has('sort')) {
// Multiorden
$sorts = explode(',', request()->sort);
foreach ($sorts as $sort) {
list($sortCol, $sortDir) = explode('|', $sort);
$query = $query->orderBy($sortCol, $sortDir);
}
} else {
$query = $query->orderBy('id', 'asc');
}
//Filtros
if ($request->exists('filter')) {
$query->where(function($q) use($request) {
$value = "%{$request->filter}%";
$q->where('name', 'like', $value)
->orWhere('address', 'like', $value);
});
}
$perPage = request()->has('per_page') ? (int) request()->per_page : null;
$pagination = $query->get()->paginate($perPage);
$pagination->appends([
'sort' => request()->sort,
'filter' => request()->filter,
'per_page' => request()->per_page
]);
return response()->json(
$pagination
);
}
Error:
Illuminate\Database\QueryException: SQLSTATE[HY000]: General error:
1096 No tables used (SQL: select * order by id asc) in file
C:\xampp\htdocs\iService\vendor\laravel\framework\src\Illuminate\Database\Connection.php
on line 664
UPDATE:
return DB::table('customers')->get();
If i use this, the api works fine, I have more apis working. The problem is that I need Query Builder to handle filters, sort, etc...
The problem was the way I instance a new query.
$query = DB::table('customers')->newQuery();
Correct:
$query = Model::query();
For my example:
$query = Customer::query();

how to fetch all records from order table in Codeigniter

$data is an array which contain user post data for fetch record from orders table
$data=array('customer_id'=>$this->input->post('custId'),'paided'=>2);
$this->db->select('*');
$this->db->from('orders');
$this->db->where($data);
$this->db->get();
$data = array(
'customer_id' => $this->input->post('custId')],
'paided' => 2
);
$this->db->select('*');
$this->db->from('orders');
$this->db->where($data);
$this->db->get();
try this :
public function function_name (){
$data = array (
'customer_id' => $this->input->post('custId'),
'paided' => 2
);
$this->db->select('*');
$this->db->from('ordere');
$this->db->where($data);
$query = $this->db->get();
return $query->result_array();
}
You have done all good just need to put result() if you get multiple row or row() if you get one row
$data=array('customer_id'=>$this->input->post('custId'),'paided'=>2);
$this->db->select('*');
$this->db->from('orders');
$this->db->where($data);
$result= $this->db->get()->result(); //added result()
print_r($result);
as simple use
$custId = $_post['custId'];
$query = $this->db->query("SELECT * FROM orders WHERE customer_id= '$custId' AND paided='2'");
$result = $query->result_array();
return $result;//result will be array
This is the plus of using framework, you don't need to write that much of code,
$where = array('customer_id' => $this->input->post('custId'),'paided'=>2)
$result = $this->db->get_where('orders', $where);
and for fetching them, use $result->row() for single record retrieval.
If you want all records, use $result->result()
Here is documentation link, if you want to learn more.
What You should need to be Correct And Why
$data=array('customer_id'=>$this->input->post('custId'),'paided'=>2);
$this->db->select('*'); // by defaul select all so no need to pass *
$this->db->from('orders');
$this->db->where($data);
$this->db->get(); // this will not return data this is just return object
So Your Code Should be
$data=array('customer_id'=>$this->input->post('custId'),'paided'=>2);
$this->db->select(); // by defaul select all so no need to pass *
$this->db->from('orders');
$this->db->where($data);
$query = $this->db->get();
$data = $query->result_array();
// or You can
$data= $this->db->get()->result_array();
here result_array() return pure array where you can also use result()
this will return array of object

codeigniter search filter model

I have created a search filter with my pagination model, When I type in my filter it does not pick up if I just have one letter for some reason my model requires that I have min 2 letters to start filtering
What is the best method in model so my search field can pick up just one letter typed in the filter input.
public function getUserGroups($limit = null, $offset = NULL) {
$this->db->select("user_group_id, name");
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->limit($limit, $offset);
$this->db->order_by('name', 'asc');
$data = array(
'name' => $this->input->post('name'),
'user_group_id' => $this->input->post('user_group_id')
);
$this->db->like($data);
$this->db->or_like('name', 'match');
$this->db->or_like('user_group_id', 'match');
$query = $this->db->get();
return $query->result_array();
}
I think following query will solve your problem
public function getUserGroups($limit = null, $offset = NULL) //better use $limit=0,$offset=0
{
$this->db->select("user_group_id, name");
$this->db->from($this->db->dbprefix . 'user_group');
$this->db->limit($limit, $offset);
$this->db->order_by('name', 'asc');
$data = array(
'name' => $this->input->post('name'),
'user_group_id' => $this->input->post('user_group_id')
);
$this->db->or_like($data);
$query = $this->db->get();
return $query->result_array();
}
Remember
They way you using like and or_like may produce wrong query.Make sure your query is producing right way as you wanted

Translate from CodeIgniter Active Record model to Laravel Eloquent

I am a CodeIgniter trying to adopt Laravel, however, I have been having a lot of problems understanding how to use Eloquent.
I suspect that if I could figure out how to translate some of my CodeIgniter Model methods to Laravel Eloquent I might be able to get on better. Hopefully, this will help others with the same problem.
Could anybody please rewrite the following from CodeIgniter to Eloquent:
public function get_products($product_id = NULL, $category_id = NULL, $limit = NULL)
{
$this->db->select('*, product.id AS product_id');
$this->db->from('product');
$this->db->join('product_unit', 'product.source_unit_id = product_unit.id', 'left');
$this->db->join('stock_levels', 'product.stock_level_id = stock_levels.id', 'left');
$this->db->join('categories', 'product.category_id = categories.cat_id', 'left');
if(isset($product_id)) {
$this->db->where('product.id', $product_id);
}
if(isset($category_id)) {
$this->db->where('product.category_id', $category_id);
}
if(isset($limit)) {
$this->db->limit($limit);
}
#$this->db->order_by('categories.cat_name', 'ASC');
$this->db->order_by('categories.cat_name', 'ASC');
$this->db->order_by('product.name', 'ASC');
$query = $this->db->get();
return $query->result_array();
}
Here's an approximate version of your query, there should be some things to tweak, but I hope you get the idea:
public function get_products($product_id = NULL, $category_id = NULL, $limit = NULL)
{
$query = Product::leftJoin('product_unit', 'source_unit_id', '=', 'product_unit.id')
->leftJoin('stock_levels', 'stock_level_id', '=', 'stock_levels.id')
->leftJoin('categories', 'category_id', '=', 'categories.cat_id');
if(isset($product_id)) {
$query->where('product.id', $product_id);
}
if(isset($category_id)) {
$query->where('product.category_id', $category_id);
}
if(isset($limit)) {
$query->limit($limit);
}
#$this->db->order_by('categories.cat_name', 'ASC');
$query->orderBy('categories.cat_name', 'ASC');
$query->orderBy('product.name', 'ASC');
dd( $query->toSql() ); /// this line will show you the sql generated and die // remove it to execute the query
return $query->get()->toArray();
}

Resources