Convert MYSQL query to Laravel way - php

I have to convert these queries to Laravel way.
$tqry = "select app_process,end_time,((end_time-".time().")/86400)as remain_day from BYAPPS_apps_data where mem_id='$valu[mem_id]' limit 1";
$tresult = $_DB->query($tqry);
$tmp=$tresult->fetchRow();
if($tmp[app_process]){
$status=$app_process[$tmp[app_process]];
if($tmp[app_process]==7&&($tmp[end_time]&&$tmp[remain_day]<=0)) $type="Expired";
}else {
$tqry = "select app_process from BYAPPS_apps_order_data where mem_id='$valu[mem_id]' order by idx desc limit 1";
$tresult = $_DB->query($tqry);
$tmp=$tresult->fetchRow();
if($tmp[app_process]) $status=$ord_process[$tmp[app_process]];
else $status="Not Customer";
}
I set the relation through the models like this.
UserInfo model
public function order()
{
return $this->hasMany('App\AppsOrderData', 'mem_id');
}
public function apps()
{
return $this->hasMany('App\AppsData', 'mem_id');
}
AppsOrderData model (=> Using 'BYAPPS_apps_order_data' table)
public function userinfo()
{
return $this->belongsTo('App\UserInfo', 'mem_id');
}
AppsData model (=> Using 'BYAPPS_apps_data' table)
public function payments()
{
return $this->hasMany('App\AppsPaymentData','mem_id');
}
Then, I tried to convert the original query in UserInfoController.php like below.
public function getUserInfoListData()
{
$userInfoListData = UserInfo::select('idx',
'mem_id',
'mem_nick',
'mem_name',
'cellno',
'ip',
'reg_date')
->with('order')
->with('apps');
$orderProcess = array('Cancel','Order', 'Confirm Order',
'Developing', 'App Uploaded', 'Service end',
'Service expired', '', '', 'Waiting');
$appsOrderData = AppsOrderData::select('app_process', 'mem_id', 'end_time');
return Datatables::of($userInfoListData)
->setRowId(function($userInfoListData) {
return $userInfoListData->idx;
})
->editColumn('type', function($eloquent) use ($appsOrderData, $orderProcess) {
if ($appsOrderData->app_process == 7 && $appsOrderData->end_time <= 0) {
return "Expired";
} else {
return "No Customer";
}
})
->editColumn('term', function($eloquent) {
return " (".$eloquent->launch_date." ~ ".now().")";
})
->orderColumn('reg_date', 'reg_date $1')
->make(true);
}
However, it doesn't return as I expected, all type data return just 'No Customer'.
How can I convert this query as laravel way?
Did I wrong make the relation?

I think there are some mistakes that you have done in your code,
AppData model doesn't have a user Relationship.
If you get() method to get data , You can do it in this way,
$userInfoListData= UserInfo ::
select('idx','mem_id','mem_nick','mem_name','cellno','ip','reg_date')
->with('order')
->with('apps')
->get();
For further reference you can use this:
Get Specific Columns Using “With()” Function in Laravel Eloquent
I hope this will help you to solve your issue- thanks!

Related

Codeigniter not getting data though available in mysql database

I have a model which fetch the data from database is below
public function counselor() {
$inst_id = $this->session->userdata('user_id');
$submission_key=$this->session->userdata('submission_key');
$query = $this->db->query("SELECT * FROM counselor where USER_ID = $inst_id AND submission_key= $submission_key");
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}
}
I have tested the $inst_id and $submission_key by printing it and its set.
$inst_id=2 and $submission_key=2016-8 .BUT though I have one record in database with those two field set its not returning the data. What is the case. I have tried with codeigniter get() and where() method too. Still not giving me the result.
Just write your query using active record function. It will help you in escaping string
$this->db->select('*',FALSE);
$this->db->where('USER_ID',$inst_id);
$this->db->where('submission_key',$submission_key);
$query=$this->db->get('counselor');
$data = $query->num_rows();
if ($data > 0) {
return $data;
} else {
return false;
}

I need to call a controller function inside a view -Codeigniter

I need to call a function from view to echo a value. I use following code,
Controller (test_controller)
public function displayCategory()
{
$this->load->model('Model_test');
$data['categories'] = $this->Model_test->getCategories();
$this->load->view('test_view', $data);
}
public function display($id)
{
$this->load->model('Model_test');
$name= $this->Model_test->getName($id);
return $name;
}
Model (Model_test)
function getCategories() {
$query = $this->db->query("SELECT * FROM category");
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
function getName($userId) {
$query = $this->db->query("SELECT name FROM user where id = '$userId' ");
if ($query->num_rows() > 0) {
return $query->row()->name;
} else {
return NULL;
}
}
View
<div id="body">
<?php
foreach ($categories as $object) {
$temp = $this->test_controller->display($object->id);
echo $object->title . " ". $object->no . $temp . '<br/>';
}
?>
</div>
but some error when running the code.
error Message: Undefined property: CI_Loader::$test_controller in view
I am not sure if you use CodeIgniter 2 or 3.
Anyway, basically you don't want to use anything inside View files except perhaps helper function(s) or some kind of "presenter" layer (that should be called inside controller I guess).
Solution using Join
Go and read this manual page and search for join. There you can learn about implementation of SQL join directive.
You want to modify this (getCategories()) function so it returns data that you require
function getCategories() {
$this->db->select('category.title, category.no, user.name as username')
->from('category')
->join('user', 'user.id = category.id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
and in view you can get your username like this
foreach ($categories as $object) {
echo $object->title . " ". $object->no . $object->username . '<br/>';
}
I am not 100% sure so please post comments I will edit this answer later.
Solution "breaking rules"
https://stackoverflow.com/a/24320884/1564365
general notes
Also consider naming your tables using plural so categories, users...
Also it is a bad practise to use "category.id as user.id" (storing user id inside category table in "id" field) instead you shold use either a pivot table or in case of 1:1 relation field "user_id".

Getting an empty array in codeigniter project

In the code below,I'm getting an empty array for the third if-else statement. What I'm trying is that get a range of date from user and showing the data from the table accordingly. My first if-else statement is returning desired results but the second one is returning empty array.
Controller:
public function bookings()
{
if($this->userlib->isLoggedIn())
{
if($this->userlib->isAdmin())
{
$this->load->view('admin_search_booking');
$date_posted_from = $this->input->post('date_posted_from');
$date_posted_till = $this->input->post('date_posted_till');
$date_posted_on = $this->input->post('date_posted_on');
if(is_null($date_posted_from) && is_null($date_posted_till) && is_null($date_posted_on))
{
$total_trails = $this->admin_panel_model->total_trail();
var_dump($total_trails);
}
elseif(!is_null($date_posted_on))
{
$total_trails = $this->admin_panel_model->filter_on_date($date_posted_on);
var_dump($total_trails);
}
elseif(!is_null($date_posted_from) && !is_null($date_posted_till))
{
$total_trails = $this->admin_panel_model->filter_by_date($date_posted_from, $date_posted_till);
var_dump($total_trails);
}
}
}
else
{
echo "User not Logged In";
}
}
Model filter_by_date :-
public function filter_by_date($date_posted_from, $date_posted_till)
{
$query = $this->db->select('*')
->where('date >=', $date_posted_from)
->where('date <=', $date_posted_till)
->get($this->search);
return $query->result();
}
isLoggedIn :-
public function isLoggedIn()
{
if($this->ci->session->email)
return true;
else
return false;
}
Change your model function like this
public function filter_by_date($date_posted_from="", $date_posted_till="")
{
$query = $this->db->select('*');
if($date_posted_from)
$this->db->where('date >=', $date_posted_from);
if($date_posted_till)
$this->db->where('date <=', $date_posted_till);
$this->db->get($this->search);
return $query->result();
}
//This may help you put your table name in your select statement and update where clause
public function filter_by_date($date_posted_from, $date_posted_till){
$date_posted_from='2015-10-10';
$date_posted_till='2015-10-16';
$query = $this->db->select('*')->from('Your_Table_Name')
->where("date >= '".$date_posted_from."'")
->where("date <= '".$date_posted_till."'")
->get($this->search);
return $query->result();
}
Use $this->db->last_query(); after filter_by_date() and check what query is actually being executed. And also make sure there are records exists in the date range you are searching for.
Or simply use straight forward query,
$Q = $this->db->query("select * from table_name where date >='".$date_posted_from."' and date <='".$date_posted_to."'");
return $Q->result_array();

Laravel - Multi fields search form

I'm builind a form with laravel to search users, this form has multiple fields like
Age (which is mandatory)
Hobbies (optional)
What the user likes (optional)
And some others to come
For the age, the user can select in the list (18+, 18-23,23-30, 30+ etc...) and my problem is that i would like to know how i can do to combine these fields into one single query that i return to the view.
For now, i have something like this :
if(Input::get('like')){
$users = User::where('gender', $user->interested_by)->has('interestedBy', Input::get('like'))->get();
if(strlen(Input::get('age')) == 3){
$input = substr(Input::get('age'),0, -1);
if(Input::get('age') == '18+' || Input::get('age') == '30+' )
{
foreach ($users as $user)
{
if($user->age($user->id) >= $input){
$result[] = $user;
// On enregistre les users étant supérieur au if plus haut
}
else
$result = [];
}
return view('search.result', ['users' => $result]);
}
elseif (strlen(Input::get('age')) == 5) {
$min = substr(Input::get('age'), 0, -3);
$max = substr(Input::get('age'), -2);
$result = array();
foreach($users as $user)
{
if($user->age($user->id) >= $min && $user->age($user->id) <= $max)
$result[] = $user;
}
return view('search.result', ['users' => $result]);
}
}
else
$users = User::all();
And so the problem is that there is gonna be 2 or 3 more optional fields coming and i would like to query for each input if empty but i don't know how to do it, i kept the age at the end because it's mandatory but i don't know if it's the good thing to do.
Actually this code works for now, but if i had an other field i don't know how i can do to query for each input, i know that i have to remove the get in my where and do it at the end but i wanna add the get for the last query..
Edit: my models :
User.php
public function interestedBy()
{
return $this->belongsToMany('App\InterestedBy');
}
And the same in InterestedBy.php
class InterestedBy extends Model{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'interested_by';
public function users()
{
return $this->belongsToMany('App\User');
}
}
you can use query builer to do this as follow
$userBuilder = User::where(DB::raw('1')); //this will return builder object to continue with the optional things
// if User model object injected using ioc container $user->newQuery() will return blank builder object
$hobbies = Request::input('hobbies') // for laravel 5
if( !empty($hobbies) )
{
$userBuilder = $userBuilder->whereIn('hobbies',$hobbies) //$hobbies is array
}
//other fields so on
$users = $userBuilder->get();
//filter by age
$age = Request::input('age');
$finalRows = $users->filter(function($q) use($age){
return $q->age >= $age; //$q will be object of User
});
//$finalRows will hold the final collection which will have only ages test passed in the filter
A way you could possible do this is using query scopes (more about that here) and then check if the optional fields have inputs.
Here is an example
Inside your User Model
//Just a few simple examples to get the hang of it.
public function scopeSearchAge($query, $age)
{
return $query->where('age', '=', $age);
});
}
public function scopeSearchHobby($query, $hobby)
{
return $query->hobby()->where('hobby', '=', $hobby);
});
}
Inside your Controller
public function search()
{
$queryBuilder = User::query();
if (Input::has('age'))
{
$queryBuilder ->searchAge(Input::get('age'));
}
if (Input::has('hobby'))
{
$queryBuilder->searchHobby(Input::get('hobby'));
}
$users= $queryBuilder->get();
}

REST API with CodeIgniter

I am creating a web-service backend for a mobile app I am developing. (I am an experience Obj-C developer, not a web-designer!) Essentially I would like to use Codeigniter and Phil Sturgeon's RESTful API Server https://github.com/philsturgeon/codeigniter-restserver however, I'm having some trouble getting it all setup and working.
I have MySQL database that is setup with data in it. And I need some help writing a CodeIgniter PHP model and controller that returns JSON data of what is inside that database. All of the tutorials and forum post's i have found deal with hardcoded data in the controler, not a MySQL database. I would ideally like to have the URL formatted like this http://api.mysite.com/v1/search?id=1&name=foo&city=bar , I could potentially have 50+ parameters to pass in the url.
Using Phil's code, I have come up with this as my controller:
public function index_get()
{
if (!$this->get('id'))
{
$this->response(NULL, 400);
}
$data = $this->grid_m->get_id($this->get('id'));
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
That only gets me one search term: id?=# .. I need to know how to get multiple search terms
Here is my Codeigniter model:
<?php
class Grid_m extends CI_Model
{
function get_all()
{
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}
This just returns EVERYTHING in my MySQL database regardless of what id or url term I pass it in the URL.
I'm a big noob when it comes to developing my own custom API so any suggestions on how to fix my controller and database model would be a huge help!
Thanks for the help!
-brian
This is old question but if somebody go here and still need help, try these code:
In your controller:
public function index_get()
{
$where = '';
if ($this->get('id')) // search by id when id passed by
{
$where .= 'id = '.$this->get('id');
}
if ($this->get('name')) // add search by name when name passed by
{
$where .= (empty($where)? '' : ' or ')."name like '%".$this->get('name')."%'";
}
if ($this->get('city')) // add search by city when city passed by
{
$where .= (empty($where)? '' : ' or ')."city like '%".$this->get('city')."%'";
}
// you can add as many as search terms
if ( ! empty($where))
{
$data = $this->grid_m->get_searched($where);
if ($data)
{
$this->response($data, 200);
}
else
{
$this->response(NULL, 404);
}
}
else
{
$this->response(NULL, 404);
}
}
In your model, create get_searched function:
class Grid_m extends CI_Model
{
function get_searched($where = NULL)
{
if ( ! is_null($where))
{
$this->db->where($where);
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
}
return FALSE;
}
}
User Codeigniter's Active record to build proper query, you can build any type of query using methods of active record, refer following example I have just added one condition in it you can add more conditions as per your need.
<?php
class Grid_m extends CI_Model
{
function get_all()
{
$this->db->select('col1, col2, col3')->where('id', 5);
$query = $this->db->get('grid');
if ($query->num_rows() > 0)
{
return $query->result();
}
return FALSE;;
}
}
Please check you query
$query = $this->db->get_where('grid', array('id' => $id));

Categories