Hello Again everyone,
can anyone help me with this code.
public function submitranking(Request $req){
$dataCandidate = Candidate::all();
foreach($dataCandidate as $Candidate){
$judgeRate = Score::where('canId',$Candidate->id )
->where('catId',$req->catId )
->where('judgeId',$req->judgeId)
->sum('score');
dd($judgeRate);
}
}
It is supposed to display all the scores of the candidates when I dd($judgeRate) it only display one record? How can I make it loop and display all the total sum scores of the candidates... Please help
You should try this:
public function submitranking(Request $req){
$dataCandidate = Candidate::get();
foreach($dataCandidate as $Candidate){
$judgeRate = Score::where('canId',$Candidate->id )
->where('catId',$req->catId )
->where('judgeId',$req->judgeId)
->sum('score');
print('<pre style="color:red;">');
print_r($judgeRate);
print('</pre>');
}
exit;
}
OR You should try this:
public function submitranking(Request $req){
$dataCandidate = Candidate::get();
foreach($dataCandidate as $Candidate){
$judgeRate = Score::select('score_id',DB::raw("SUM(score) as score"))
->where('canId',$Candidate->id )
->where('catId',$req->catId )
->where('judgeId',$req->judgeId)
->get();
print('<pre style="color:red;">');
print_r($judgeRate);
print('</pre>');
}
exit;
}
You can use pluck function to get all ids of candidates and use whereIn.
So, there is no need to use loop, use group by and simple raw query.
Just change your function like,
public function submitranking(Request $req){
$dataCandidate = Candidate::all()->pluck('canId');
$judgeRate = Score::whereIn('canId',$dataCandidate)
->where('catId',$req->catId )
->where('judgeId',$req->judgeId)
->select('catId',DB::raw('COUNT(score) as total_score'))
->groupBy('catId')
->get();
dd($judgeRate);
}
You can see docs here: https://laravel.com/docs/5.5/queries#where-clauses
Hope you understand.
Related
I want to create simple search function. I follow some example. but I was unable to get results. please help me.
//control page
public function search(){
$key = $this->input->post('phone1',TRUE);
$data['ppp'] = $this->admin_model->searching($key);
$this->load->view('members/search_result',$data);
}
//Model page
public function searching($key){
$this->db->like('phone1',$key);
$query = $this->db->get('advertisement');
return $query->result();
}
try to print query
$query = $this->db->get('advertisement');
echo $this->db->last_query();exit;
try and check that query in your database is that giving result or not
I have a homework table in laravel-5.7 where 5000 records in the table also have some Relational records that are coming through HasMany() or HasOne() Relation. I tried many types of Eloquent Queries to get fast results. but Postman result time becomes 10200ms to 10700ms but when i direct dispaly this into postman then i am getting this into 500ms to 1100ms. i want to get it in near about 800ms after binding form Laravel Resource or Normal Array.
problem is, when i try to show the Eloquent result direct then it coming around 600ms to 1000ms. but when i bind into an Array and display in postman then its taking 6200ms why? i do not know?
$page = $req->page ?$req->page:1; // set starting value for look query limit.
$user = Auth::user()->student()->first();
$studentProfile = Auth::user()->student()->first();
// collecting all homework id that have assigned to student.
$studentHWList = StudentHomeWork::where("student_id",$studentProfile->id)
->select('home_work_id')
->get()->pluck('home_work_id');
// collecting page by page of homework id.
$hwLimitList = Homework::where('session_code', dnc($req->require('sid')))
->whereIn('id',$studentHWList )
->where('approved', '1')
->select('id')
->orderBy('updated_at','desc')
->get();
$hwIndexes = $hwLimitList->pluck('id')->forPage($page,$this->recordLimit);
$paginated = Homework::whereIn('id', $hwIndexes)
->with( "user:id,username,name",
'subject:id,subject_name,subject_code',
'approveByUser','publishBy')
->with(["likes"=>function($erw){
$erw->select('id','home_work_id','complete_status','likes')
->where("student_id", $studentProfile->id);
}])
->with(['comment'=>function($qur){
$qur->where('parent_id',0)
->where('user_id',$user->id);
}])
->orderBy('id','desc')
->get( );
if( count($paginated))
{
$paginationData = customPagination('getAllHW',$hwLimitList , $page , $this->recordLimit , $user, $studentProfile );
return response()->json(["error"=>0,"errmsg"=>"","paginationData"=>$paginationData ,
"response"=>['homework_list'=>$this->customResourceHWBinding($paginated , $req )],'auth'=>userType()]);
private function customResourceHWBinding($queryData , $request, $user, $studentProfile )
{
$document_list =[]; $is_seen=0; $resultData =[];
foreach ( $queryData as $query )
{
if( count($query->document) )
{
foreach($query->document as $document){
if( $document->changed_filename )
{
$file=""; $fileName ="";
$path =env('AWS_URL')."/uploads/".dnc($request->header('dbauth'))."/".$query->session_code."/homeWorks/";
if(is_s3FileExist( $path.$document->changed_filename ) )
{
$fileName =$document->changed_filename;
}
$document_list[] = [
'oname'=> $document->changed_filename,
'ext'=>$fileName?explode('.', $document->changed_filename):"",
'url'=>$file,
'file_url'=>$document->changed_filename?$path.$document->changed_filename:""
];
}
}
}
$resultData[] = [
'id'=>enc($query->id),
'ids'=>$query->id,
'pin_user_id'=>"",
'pin_enabled'=>0,
'created_by'=>$query->user->name,
'created_by_image'=>getUserImage($query->user,$query->user->privilege,$request),
'assignment_date'=>getDateFormat($query->assignment_date,0),
'assigment_date_edit'=>"",
'submission_date'=>getDateFormat($query->submission_date,1),
'submission_date_edit'=>"",
'class_code'=>$query->class_code,
'subject'=>$query->subject?$query->subject->subject_name:"",
'topic'=>$query->topic,
'is_student_seen'=> $this->studentHWSeen($query, $user, $studentProfile),
'updated_at'=> date('d-m-Y H:i:s' , strtotime($query->updated_at)),
'approved'=>$query->approved,
'approve_by'=> '',
'can_approve'=>0,
'comment_count'=>0,
'total_like'=>0,
'documents_count'=>count($document_list)?count($document_list):0,
'is_draft'=> $query->draft?$query->draft:0,
];
}
return $resultData;
}
private function studentHWSeen( $query , $user, $studentProfile)
{
if(count($query->studentSeen))
{
foreach($query->studentSeen as $seen){
if( user->privilege == 1 )
{
if($seen->student_id == $studentProfile->id )
return 1;
}
}
}
return 0;
}
I try to use Resource but it's also taking 3+seconds. I try too many others optimize a solution but not work in my case. someone told Use query builder instead of Eloquent to optimize queries. find here Optimising Laravel query . is it a good answer for me? I am not sure. please help me.
please check my image.
Eloquent Query Result
First of all, try to optimize this:
$paginated = Homework::whereIn('id', $hwIndexes)
->with( "user:id,username,name",'subject:id,subject_name,subject_code',
'approveByUser','publishBy')
->with(["likes"=>function($erw){
$erw->select('id','home_work_id','complete_status','likes')
->where("student_id",Auth::user()->student()->first()->id);
}])
->with(['comment'=>function($qur){
$qur->where('parent_id',0)
->where('user_id',Auth::id());
}])
->orderBy('id','desc')
->get( );
You run same code in nested query: Auth::user()->student()->first()->id.
Optimized version:
$studentId = Auth::user()->student()->first()->id;
$paginated = Homework::whereIn('id', $hwIndexes)
->with("user:id,username,name", 'subject:id,subject_name,subject_code', 'approveByUser', 'publishBy')
->with(["likes"=>function($erw) use ($studentId) {
$erw->select('id','home_work_id','complete_status','likes')
->where("student_id", $studentId);
}])
->with(['comment'=>function($qur) {
$qur->where('parent_id',0)
->where('user_id',Auth::id());
}])
->orderBy('id', 'desc')
->get();
Remember to add indexes to fields that you're using in where conditions.
I want to get the latest timestamp. For some reason, when I try to use sortBy or orderBy, it doesn't work. Can anyone help me?
Here is the codes that I tried:
public function getTest($id) {
$data = test::where('user_id', $id)->sortByDesc('created_at')->get();
// I also tried doing this
$data = test::where('user_id', $id)->orderBy('created_at', 'desc')->get();
if(count($data)>0) {
return view('test', compact('data'));
}
else {
return view('test');
}
}
Try:
$data = test::where('user_id', $id)->orderBy('created_at', 'desc')->first();
This will order the rows in table by created_at.
Hope this helps you!
If you want to get the oldest created_at it would be easier to query like
$data = test::where('user_id', ,'=', $id)->oldest();
to get the user's test in descending order.
Here's a "pro" tip: You should set up a relation between Test und User. And typehint your method (your route would look like Route::get'(/users/{user}/tests', 'UserTestsController#index');. You then could write your query like:
public function index(User $user)
{
$data = $user->tests()->oldest();
return view('tests.index')
->with('data', $data);
}
I have to table article and table comment. In the home page I want to see how many comment for earch article.
Model
function show_latest_article($start,$display,$cate)
{
$query= $this->db->get_where('news_news', array('News_Cate_ID'=>$cate),$start,$display);
if($cate==0)
{
$query= $this->db->get_where('news_news',$start,$display);
}
return $query->result();
}
function count_comment($id)
{
$query = $this->db->get_where('comment',array('comment_article_id'=>$id) );
return $query->num_rows();
}
Controller
function index() {
$this->load->model('article');
$data=array('article'=>$this->article->show_latest_article(0,8,1),
'sidebar'=>$this->article->side_bar(9),
'count_comment'=> $this->article->count_comment($id),
);
$this->load->view('page/index',$data);
}
In the view I have this
foreach($article as $art)
{
echo $art->title."<br>";
$id= $art->id;
// I want to echo number of comment here.
// Or I want to call function count_comment($id)
}
$this->load->model('article');
$data['article'] = $this->article->show_latest_article(0, 8, 1);
$data['sidebar'] => $this->article->side_bar(9);
$data['count_comment'] => $this->article->count_comment($id);
$this->load->view('page/index', $data);
And it should work.
It's not so clear, where the $id variable come from, but I suggest to join the comments table to your article. It's not a best practice to make queries within loops.
In your model:
public function show_latest_article($ids = array())
{
return $this->db
->select('articles.*, COUNT(comments.id) as comment_count')
->where_in('articles.id', $ids) // You can skip this
->join('comments', 'comments.article_id = articles.id', 'left')
->group_by('articles.id')
->get('articles')
->result();
}
In your controller:
public function index()
{
$data['articles'] = $this->article->show_latest_article(array(0, 8, 1));
$this->load->view('page/index', $data);
}
Just change the field name according to database columns. Also you can skip the where_in condition. (I'm not sure what the three number stands for).
Then in your view, you can simply access the field:
$art->comment_count
EDIT: According to your comment:
$this->db
->select('a.*, (SELECT COUNT(*) FROM comment c WHERE c.comment_article_id = a.News_News_ID ) as counta')
->get('news_news')
->result();
I am writing this answer as you provided code. It could be more simpler if you give more database details. Try below code
function index() {
$this->load->model('article');
$articles = $this->article->show_latest_article(0,8,1);
foreach($articles as $article)
{
$article->comment_count = $this->article->count_comment($article->id);
$all_article[] = $article;
}
$data=array('article'=>$all_article,
'sidebar'=>$this->article->side_bar(9)
);
$this->load->view('page/index',$data);
}
On view
foreach($article as $art)
{
echo $art->title."<br>";
$id= $art->id;
echo $art->comment_count;
}
Controller :
function index() {
$this->load->model('article');
$articles = $this->article->show_latest_article(0,8,1);
$count_comments = Array();
for($i=0;$i<count($articles);$i++){
$count_comments[$i] = $this->article->count_comment($articles->$id);
}
$count_comments =
$data=array('article'=>$articles,
'sidebar'=>$this->article->side_bar(9),
'count_comment'=> $count_comments);
$this->load->view('page/index',$data);
}
In the View :
$i=0;
foreach($article as $art)
{
echo $art->title."<br>";
$id= $art->id;
echo $count_comment[$i];
$i++;
}
Data is passed from the controller to the view by way of an array or an object in the second parameter of the view loading function. Here is an example using an array:
$data = array(
'title' => 'My Title',
'heading' => 'My Heading',
'message' => 'My Message'
);
$this->load->view('blogview', $data);
Also below is the example for object
$data = new Someclass();
$this->load->view('blogview', $data);
PLEASE NOTE: Note: If you use an object, the class variables will be turned into array elements.
You can find out more from below ref URL
Ref: https://ellislab.com/codeigniter/user-guide/general/views.html
First of all in your controller you get count_comment only for specific article ID and not for all articles so you cant do foreach to display comment count of each article.
You need to setup you model better and in model function show_latest_article to use JOIN comments table and do count comment in query.
I will help you with query if you provide me more info about database table of article and comments.
SELECT
article.*,
COUNT(comment.id),0) AS numberOfCommments
FROM article
LEFT JOIN comment
ON comment.article_id = article.id
GROUP BY article.id
I have to search for multiple values in a field using mysql in codeigniter. Here follows my code.
In Controller
public function vpsearch()
{
$data['info'] = $this->psearch_m->emp_search_form();
$this->load->view("employer/result",$data);
}
IN Model
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
$jrole = $this->input->post('ps_jobrole'));
if ( $jrole !== NULL)
{
return $this->db->get('js_edu_details');
$this->db->like('js_skills','$skill');
}
}
In view i.e, (../employer/result)
foreach($info->result() as $row)
{
echo $row->js_id."<br/><br/>" ;
}
However I am getting all the records in 'js_edu_details' table instead of fields having searched 'skills'.
Where I am going wrong? Any help wud b appreciated, thanx in advance.
Try:
public function emp_search_form()
{
$skill = $this->security->xss_clean($this->input->post('ps_skills'));
//$skill = $this->input->post('ps_skills', true); other short way of getting the above result with `xss clean`
if ( $jrole !== NULL)
{
$this->db->like('js_skills',$skill); #remove the single quote around the `$skill`
$res = $this->db->get('js_edu_details');
echo $this->db->last_query(); #try to print the query generated
return $res;
}
}
Return statement should be after the like statement
You should arrange the code properly like this
public function emp_search_form()
{
$ps_skills = $this->input->post('ps_skills')
$skill = $this->security->xss_clean($ps_skills);
if ( $jrole !== NULL)
{
$this->db->like('js_skills','$skill');
return $this->db->get('js_edu_details');
}
}
Also you should note the condition will never meet. It will always give error undefined variable $jrole