I have two tables Project and User and a join table ProjectUser. I am creating a query to select the users under a certain projectName I couldn't do that so I created a query to select the id of the project according to its name from the project table
public function findName($projectName){
$query=$this->getEntityManager()
->createQuery("SELECT p.id FROM SocialProProjectBundle:Project p WHERE ``p.name='$projectName'");
return $query->getResult();
}
and then a query to select the users through the project id
public function findProjectUsers($pId){
$query=$this->getEntityManager()
->createQuery(
"SELECT pu, u FROM SocialProProjectBundle:ProjectUser pu JOIN SocialProDefaultBundle: User u WHERE pu.project = '$pId'"
);
return $query->getResult();
}
but I always get Notice: Array to string conversion !!!!!
Here is how I called them in the controller
$projectName = $request->get('projectName');
echo($projectName);
$projectId=$this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findName($projectName);
echo(count($projectId));
foreach($projectId as $pId) {
$pus = $this->getDoctrine()->getRepository('SocialProMeetingBundle:meetingUser')->findProjectUsers($pId);
}
$response = "<select class=\"select2_multiple form-control\" multiple=\"multiple\">";
foreach ($pus as $user) {//($i=0;$i<count($pus);$i++)
$name[]=array($user->getFirstName());
}
$response = $response . "<option>$name</option>";
$response = $response."</select> ";
return new Response($response);
//return($pus);
//call repository function
}
Hi: for the for loop question you had on how to solve it, use this code:
$response = "<select class=\"select2_multiple form-control\" multiple=\"multiple\">";
foreach($pus as $user){
$response . "<option>" . $user->getFirstName() . "</option>";
}
$response = $response."</select> ";
The solution I found to this is that I avoided the $pId and found the query capable to select the users through the $projectName Here it Is :
public function findProjectUsers($projectName){
$query=$this->getEntityManager()
->createQuery(
"SELECT u.firstName FROM SocialProDefaultBundle:User u, SocialProProjectBundle:Project p, SocialProProjectBundle:ProjectUser pu WHERE u.id = pu.user AND p.id=pu.project AND p.name='$projectName'");
return $query->getResult();
}
Related
Problem: WP_Query search string needs to look into the taxonomy name.
By default, $args['s'] only searches inside the title, content, and excerpt, but I need to search inside a custom taxonomy name too. I tried with tax_query, but it doesn't have the name__like or LIKE operator for tax_query.
So, Now I'm trying to achieve it with the custom query; here's my code:
$keyword = "Monster";
$args['s'] = $keyword;
add_filter('posts_join', 'filter_post_join', 10, 1);
add_filter('posts_where', 'filter_post_where', 10, 1);
$posts = new WP_Query($args);
function filter_post_join( $join ) {
global $wpdb;
$join .= " LEFT JOIN $wpdb->term_relationships as txr ON ( {$wpdb->posts}.ID = txr.object_id )";
$join .= " LEFT JOIN $wpdb->terms as trms on ( txr.term_taxonomy_id = trms.term_id )";
return $join;
}
function filter_post_where( $where ) {
global $keyword;
$where .= " AND trms.name LIKE $keyword";
return $where;
}
Can anyone please tell me what I am doing wrong here?
I found a solution that kind of works: https://gist.github.com/markoman78/e22bbebe0d2305f294eb554d5a39d8c3
But it has a problem, it doesn't filter post_type; if I want to fetch posts from 'x' post type it will also fetch posts from other posts type that has matching tags name
Hello,
I am working on a Posts and Comment Models response API in Code Igniter!
MY Controller:
public function getPosts()
{
if (isset($_POST["getPosts"]))
{
$data = $this->api_model->getPosts();
$json_response2 = array('status' => 'success', 'postList' => $data->result_array());
echo json_encode($json_response2);
}
else
{
$data['status'] = 'error';
echo json_encode($data);
}
}
My Model:
public function get_posts()
{
$this->db->order_by('postID', 'DESC');
$query = $this->db->get('posts');
return $query->result_array();
}
MYSQL Tables:
for Posts---
postID | postTitle | postBody
for Comments---
commentID | postID | commentBody
I want to Get Comments Count for post Array in API response to display list of posts and comments Count for that Post?
ThankYou!
This is the query needed for you to get all those data in single query. It will join both table with left join clause and will give you the comment count as well.
SELECT
p.`postID`,
`postTitle`,
`postBody`,
COUNT(c.commentID) AS comment_cnt
FROM
`Posts` AS p
LEFT JOIN `Comments` AS c
ON p.postID = c.postID
GROUP BY c.postID
ORDER BY p.postID DESC ;
N:B left join is mandatory, otherwise it will not give you zero
commented post.
to convert it to codeigniter you can write it as.
$this->db->from('Posts p');
$this->db->join('Comments c','p.postID = c.postID','left');
$this->db->group_by('c.postID');
$this->db->order_by('p.postID', 'DESC');
$this->db->select('p.*,COUNT(c.commentID) AS comment_cnt');
$query = $this->db->get();
$res = $query->result_array();
Hope this would help you.
You need to join your comments table to get count and group by your postID.
Modify your get_posts() function in model as follows:
$this->db->from('posts');
$this->db->select("posts.*, count(*) as comments_count");
$this->db->join('comments', 'posts.postID = comments.postID');
$this->db->group_by('posts.postID');
$this->db->order_by('postID', 'DESC');
return $this->db->get()->result_array();
Also, you are using result_array() twice which is wrong. Change your controller line
$json_response2 = array('status' => 'success', 'postList' => $data->result_array());
as
$json_response2 = array('status' => 'success', 'postList' => $data);
because you are already getting result from model.
Also, use the correct name for function in controller, $this->api_model->get_posts();
Hope it helps.
Can somebody help me convert this Sql Query
SELECT *
FROM customer c
LEFT JOIN customer_order co
ON c.customer_number = co.customer_number
AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid'
AND c.order_status = 'unserve'
AND co.cus_ord_no IS null
into Codeigniter query just like the image below for example
When query statements do not have clauses that need to change conditionally then using $this->db-query() is the way to go.
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co
ON c.customer_number=co.customer_number AND co.order_status IN ('preparing', 'prepared')
WHERE c.customer_status='unpaid' AND c.order_status='unserve' AND co.cus_ord_no IS null";
$query = $this->db->query($sql)->result();
echo json_encode($query);
It might be wise to include a check on the return from query() though because if it fails (returns false) then the call to result() will throw an exception. One way that can be handled is like this.
$query = $this->db->query($sql);
if($query !== FALSE)
{
echo json_encode($query->result());
return;
}
echo json_encode([]); // respond with an empty array
Query Builder (QB) is a nice tool, but it is often overkill. It adds a lot of overhead to create a string that literally is passed to $db->query(). If you know the string and it doesn't need to be restructured for some reason you don't need QB.
QB is most useful when you want to make changes to your query statement conditionally. Sorting might be one possible case.
if($order === 'desc'){
$this->db->order_by('somefield','DESC');
} else {
$this->db->order_by('somefield','ASC');
}
$results = $this->db
->where('other_field', "Foo")
->get('some_table')
->result();
So if the value of $order is 'desc' the query statement would be
SELECT * FROM some_table WHERE other_field = 'Foo' ORDER BY somefield 'DESC'
But if you insist on using Query Builder I believe this your answer
$query = $this->db
->join('customer_order co', "c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared')", 'left')
->where('c.customer_status','unpaid')
->where('c.order_status','unserve')
->where('co.cus_ord_no IS NULL')
->get('customer c');
//another variation on how to check that the query worked
$result = $query ? $query->result() : [];
echo json_encode($result);
You can do
public function view_customers()
{
$sql = "SELECT * FROM customer c LEFT JOIN customer_order co ON c.customer_number = co.customer_number AND co.order_status IN ('preparing', 'prepared') WHERE c.customer_status='unpaid' AND c.order_status = 'unserve' AND co.cus_ord_no IS null";
return $this->db->query($sql)->result();
}
You can use row() for one output to object, or row_array() if one output but array. result() is multiple objects and result_array() is multiple arrays.
My way do usually is like this:
Controller:
public function view()
{
$this->load->model('My_Model');
$data = new stdclass;
$data->user_lists = $this->my_model->view_users(array('nationality'=>'AMERICAN'));
}
Model:
public function view_users($param = null) //no value passed
{
$condition = '1';
if (!empty($param)) { //Having this will trap if you input an array or not
foreach ($param as $key=>$val) {
$condition .= " AND {$key}='{$val}'"; //Use double quote so the data $key and $val will be read.
}
}
$sql = "SELECT * FROM users WHERE {$condition}"; //Use double quote so the data $condition will be read.
// Final out is this "SELECT * FROM users WHERE 1 AND nationality='AMERICAN'";
return $this->db->query($sql)->result();
}
I want to run following query in symfony doctrine.
SELECT p.id AS id FROM skiChaletPrice p WHERE ski_chalet_id = ? AND month = ?
I wrote my doctrine query as following.
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$result = $q->fetchOne();
if ($result->count() > 0) {
return $result->toArray();
} else {
return null;
}
But my result always include all columns in the table. What the issue? Please help me.
The issue is that fetchOne() will return a Doctrine object, which implicitly contains all the columns in the table. $result->toArray() is converting that doctrine object to an array, which is why you get all the columns.
If you only want a subset of column, don't hydrate an object, instead do something like this:
$q = Doctrine_Query::create()
->select('p.id AS id')
->from('skiChaletPrice p')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from);
$results = $q->execute(array(), Doctrine::HYDRATE_SCALAR);
See http://docs.doctrine-project.org/projects/doctrine1/en/latest/en/manual/data-hydrators.html
This is how I should do it:
$result = Doctrine_Query::create()
->select('id')
->from('skiChaletPrice')
->andWhere('ski_chalet_id = ?', $chaletId)
->andWhere('month = ?', $from)
->limit(1)
->fetchOne(array(), Doctrine_Core::HYDRATE_SINGLE_SCALAR);
// result will be a single id or 0
return $result ?: 0;
// if you want array($id) or array() inseatd
// return (array) $result;
Here's some code adapted from phpBB. Near as I can tell it's trying to delete all topics wherein the only poster is the target user.
(note that for testing purposes I changed the final query from a DELETE to a SELECT)
<?php
$user_id = 66275;
mysql_connect('localhost', 'username', 'password');
mysql_select_db('db_name');
$start = microtime(true);
$total = 0;
define('POSTS_TABLE', 'phpbb_posts');
define('TOPICS_TABLE', 'phpbb_topics');
$sql = 'SELECT topic_id, COUNT(post_id) AS total_posts
FROM ' . POSTS_TABLE . "
WHERE poster_id = $user_id
GROUP BY topic_id";
$result = mysql_query($sql);
$topic_id_ary = array();
while ($row = mysql_fetch_assoc($result))
{
$topic_id_ary[$row['topic_id']] = $row['total_posts'];
}
mysql_free_result($result);
if (sizeof($topic_id_ary))
{
$sql = 'SELECT topic_id, topic_replies, topic_replies_real
FROM ' . TOPICS_TABLE . '
WHERE ' . sql_in_set('topic_id', array_keys($topic_id_ary));
$result = mysql_query($sql);
$del_topic_ary = array();
while ($row = mysql_fetch_assoc($result))
{
if (max($row['topic_replies'], $row['topic_replies_real']) + 1 == $topic_id_ary[$row['topic_id']])
{
$del_topic_ary[] = $row['topic_id'];
}
}
mysql_free_result($result);
if (sizeof($del_topic_ary))
{
$sql = 'SELECT topic_id FROM ' . TOPICS_TABLE . '
WHERE ' . sql_in_set('topic_id', $del_topic_ary);
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result))
{
$total++;
echo $row[topic_id] . "\r\n";
}
}
}
function sql_in_set($field, $array, $negate = false, $allow_empty_set = false)
{
if (!sizeof($array))
{
if (!$allow_empty_set)
{
// Print the backtrace to help identifying the location of the problematic code
$this->sql_error('No values specified for SQL IN comparison');
}
else
{
// NOT IN () actually means everything so use a tautology
if ($negate)
{
return '1=1';
}
// IN () actually means nothing so use a contradiction
else
{
return '1=0';
}
}
}
if (!is_array($array))
{
$array = array($array);
}
if (sizeof($array) == 1)
{
#reset($array);
$var = current($array);
return $field . ($negate ? ' <> ' : ' = ') . $var;
}
else
{
return $field . ($negate ? ' NOT IN ' : ' IN ') . '(' . implode(', ', $array) . ')';
}
}
$elapsed = microtime(true) - $start;
echo "\r\ntook $elapsed seconds";
echo "\r\ngot $total rows back";
?>
This does three queries. First gets all the topics the target user has posted in and the number of times they've posted in each topic. The second gets how many replies each topic in the first query actually has. Then there's some PHP code to see which topics have had all their posts made by the target user. After that the code (prior to my changes) DELETEs all those topics.
Overall it seems to me that this could be written better by doing something like this:
SELECT t.topic_id
FROM phpbb_topics AS t
JOIN phpbb_posts AS p1
ON p1.topic_id = t.topic_id
AND p1.poster_id = $poster_id
LEFT JOIN phpbb_posts AS p2
ON p2.topic_id = t.topic_id
AND p2.poster_id <> $poster_id
WHERE p2.poster_id IS NULL;
Or maybe this:
SELECT t.topic_id
FROM phpbb_topics AS t
JOIN phpbb_posts AS p1
ON p1.topic_id = t.topic_id
AND p1.poster_id = $poster_id
AND t.topic_poster = $poster_id
AND t.topic_last_poster_id = $poster_id
LEFT JOIN phpbb_posts AS p2
ON p2.topic_id = t.topic_id
AND p2.poster_id <> $poster_id
WHERE p2.poster_id IS NULL
Testing this is actually quite difficult thanks to MySQLs caching but... from what testing I have been able to do it seems like the way phpBB is currently doing it is in fact faster. Which is surprising to me.
Any ideas?
It looks to me like you are on the right track. Try adding indexes to all the columns you are using in the joins as this can often drastically increase the speed of joins.