Yii2: How to use another query in orderBy - php

I have created fc_forum_post table, that one of the columns is is_question when this column equal 1 means the row is question and when the column equal with 0 means the row is an answer.
Now I want to sort my grid view with status = 2 ether question or answer.
As a matter of fact, I want to sort query with another query.
Something like this:
$query = ForumPost::find()
->select([
'forum_post.*',
'waiting' => ForumPost::find()
->select('COUNT(*)')
->where('forum_post.is_question = 0')
->andWhere('forum_post.status = 2')
->andWhere('question_sub = forum_post.id')
])
->joinWith(['category', 'user'])
->where(['forum_post.is_question' => 1])
->orderBy([
'waiting' => SORT_DESC
'forum_post.status' => SORT_DESC
]);
I have tried this query for my gridview. Actually I want to have answer count column an sort with this column.
question title
answer count
title one
4
title two
3
question title = forum_post.is_question = 1
answer count = forum_post.is_question = 0
If you have any question for understanding better my problem, ask me and I will appreciated for help me to solve my problem.

Related

How do I sort if the information is in a different Laravel table?

Initially, I had an enum list and this sorting was written for it (everything works well)
->orderByRaw("CASE state
WHEN 'Open' THEN 1
WHEN 'Active' THEN 2
WHEN 'Closed' THEN 3
ELSE 4
END")
This was an enum list of project states
How do I make the code above work? So that it works with another table (states), also sorting.
I have projects table that contains state_id column and I have states table that contains id and state_name
I know I can set the correct order in the states table
and then sort - - - > order By ('state_id'). However, this is wrong, I think.
Easy solution is to put a new field named priority to your states table which is an unsigned tiny integer then you can easily sort by priority field
$projects = Project::join('states', 'states.id', '=', 'projects.state_id')
->orderBy('states.priority', 'asc')->select('projects.*')->get();
dd($projects->toArray());
and if you insist to sort by states.state_name you can do this
$projects = Project::join('states', 'states.id', '=', 'projects.state_id')
->orderByRaw("CASE states.state_name
WHEN 'Open' THEN 1
WHEN 'Active' THEN 2
WHEN 'Closed' THEN 3
ELSE 4
END")->select('projects.*')->get();
dd($projects->toArray());
I recommend using ORDER BY FIELD
$value = DB::table('projects')->join('states', 'projects.state_id', 'states.id')
->where('states.state_name', '!=', 'Process')
->orderByRaw("FIELD(state_name,'Open','Active','Closed')")
->paginate(7);

Row Count using one SQL String [duplicate]

This question already has an answer here:
Using Google charts with php/mysqli - cannot get it working
(1 answer)
Closed 3 years ago.
I am pondering if there is away that I can count different values from different columns using one SQL Query.
I am making Graphs on my website and I want it to count No values in rows I was thinking to use the following
$sql="SELECT incident.ppe, incident.induction, incident.actions, incident.ssops
FROM incident WHERE ppe = 'No' OR induction = 'No' OR actions = 'No' OR ssops = 'No'
AND YEAR(date) = YEAR(CURDATE())
AND client_id = '$slcustom1'"
The values are Yes and No Values. What my aim is is to echo the value of each Column in the graph values I am using.
var data = google.visualization.arrayToDataTable([
['', ''],
['PPE', 11], // Value 11 should be row counts of all the No's same with all values below
['Induction', 2],
['Actions', 2],
['SSOPs', 2]
Currently I do a SQL query for each value but this is making my code very long and untidy. Any suggestions would be appreciated. Group by will also work but how do I echo each result to the Graph value
You can combine SUM() and IF() functions to count all 'No' in selected rows like this.
SELECT
SUM(IF(incident.ppe = 'No', 1, 0)),
SUM(IF(incident.induction = 'No', 1, 0)),
SUM(IF(incident.actions = 'No', 1, 0)),
SUM(IF(incident.ssops = 'No', 1, 0))
FROM incident
The IF() function will assign value 1 to the rows where the condition is true (where the attribute value is equal to 'No') and 0 to other rows. SUM() will then count a total of all rows. So if there are 5 'No' in ppe from a total of 9 rows the SUM() result will be 1+1+1+1+1+0+0+0+0=5

Counting multiple vote choices in Doctrine with createQueryBuilder

I'm working on a voting system, where user will be able to vote either yes, no or not sure to a given question.
These are being stored in a voteOptions table as choice with a value of either 0, 1 and 2 which is attached to a vote table that stores additional information. I struggling to work out how to count up the votes in a single function.
The function below counts a single choice, which I currently call once for each voteOption. I'm counting distinct users as they can appear more than once, but only their last vote counts:
public function countPollVotesByIsCurrentAndChoice(Poll $poll, $choice) {
return $this->createQueryBuilder('v')
->leftJoin('v.voteOptions', 'vo')
->andWhere('v.poll = :poll')
->andWhere('v.isCurrentVote = :isCurrentVote')
->andWhere('vo.choice = :choice')
->setParameters(['isCurrentVote' => true, 'poll' => $poll, 'choice' => $choice])
->select('COUNT(DISTINCT v.user) AS vote_count')
->getQuery()
->getSingleScalarResult();
}
But I'd prefer to make a single call to get all 3 counts. I would really appreciate any advice about how best to do this.
You have to use COUNT() together with GROUP BY which will aggregate the choices to three possible answers and the COUNT function counts the number of records for each answer.
$query = $em->createQuery('SELECT count(vo.choice) AS cnt FROM AppBundle:Vote v JOIN v.voteOptions vo WHERE ... GROUP BY vo.choice');
$result = $query->getResult();
This query will not return an array with Vote objects but just an array with rows that contains columnames and values. print_r() will help you

Codeigniter-returns only one row from my model class

I have written a model code where i am joining two tables, and returning my results.
I have 26 results in my table ,but the code below i mention is returning only one rows! What could be the reason?Why its returning only one rows?
Please help me regarding this problem
Update
Table structure
question
-----------
question_id PK Auto_Incr
question varchar...
votes int
answer
------------
answer_id PK Auto_icre
question_id FK refrences question
content longtext
From the below table structure my model code is showing only 2 question count, skipping the last question, After little research i found the reason why it is not counting my third question, it is because it does not have any answer in my answer table.
I want, if no answer then it should show count=0 for the particular question, How can to solve this issue?
Table Data structure data:
question
-----------
question_id question votes
1 what's name? 0
2 where you? 3
3 blah blah 9
answer
----------
answer_id question_id content
4 2 India
5 2 Nepal
6 2 Pakistan
7 1 Mr Osama Binladan
Model
public function fetch_allquestions($limit, $start)
{
$this->load->database();
$this->db->limit($limit, $start);
$this->db->from('question');
$select =array(
'question.*',
'userdetails.*',
'COUNT(answer.answer_id) AS `Answers`'
);
$this->db->select($select);
$this->db->join('answer','answer.question_id = question.question_id');
$this->db->join('userdetails','userdetails.user_id = question.user_id');
$query = $this->db->get();
print_r("Number of rows=".$query->num_rows());//showing only One, out of 26 rows
if ($query->num_rows() > 0)
{
foreach ($query->result() as $row)
{
$data[] = $row;
}
return $data;
}else{
return false;
}
}
You have a COUNT() sql aggregation in the select. Since you don't have any GROUP BY, the database will use the whole result set as one implicit group thus reducing your resultset to one row when counting it all up. This is how sql should work.
You can check out the generated sql query with print $this->db->last_query() right after the $this->db->get(); line, and run it in your sql console to see what's happening.
You probably wanted to add a $this->db->group_by('question.question_id'); or something similar.

find value of row out of 3 columns in php and mysql

How can i find 3 in row id#1 with 4 columns in php
id, Content_type1, Content_type2, Content_type3
1 6 3 9
You should restate your question with some context included. Not sure if you're looking for values in that column, or only if the value is 3?
$sql = "SELECT Content_type2 FROM [yourTableHere] WHERE Content_type2 = 3
mysql_query($sql);
That query will get that exact value. If you want to get that value for all records, remove the WHERE clause.
I'll have to say:
$sql = 'SELECT Content_type2 FROM some_table';
$rs = mysql_query($sql);
$row = mysql_fetch_assoc($rs);
echo $row['Content_type2'];
This will fetch the value from Content_type2 assuming there's exactly one row in that table. If there's more than one row or if there's some other logic you want to apply in order to determine what value to use, please clarify.
If you're looking to just return a row that has a value your looking for, then you can use something like the following for your SQL satement:
SELECT * FROM [TABLE] WHERE Content_type1 = [SEARCH] OR Content_type2 = [SEARCH] OR Content_type3 = [SEARCH]
Where [TABLE] is your table name and [SEARCH] is the value you're looking for.
If you want to know which specific column had the value, you'll have to sift through the returned rows to figure that out.

Categories