mysql - Add many-to-many select into existing query -
i have query set return comments given 1 user another.
now want allow ability rate these comments.
i've added new table has 3 fields: comment_id, user_id, , score.
how can grab array of {user_id,score} comment fetched?
will need loop through comments after fetched , run second query? approach result in adding several queries.
can done single query?
here's function have now:
function getallcomments($args) { if(empty($_session['user']['id'])) return false; $limit = 5; if(isset($args['limit'])) $limit = $args['limit']; $page = 1; if(isset($args['page'])) $page = $args['page']; $data = array(); $offset = ($page-1)*$limit; $sql = "select c.*,concat(u1.firstname,' ',u1.lastname) owner,u1.title ownertitle,concat_ws(' ',u2.firstname,u2.lastname) sendername,u2.title sendertitle,a.name actionname,a.behavior comment c join user u1 on c.recipient = u1.id join user u2 on c.sender = u2.id join action on c.action = a.id c.type=1"; if(isset($args['location'])) $sql .= " , u1.location=?"; $sql .= " order date desc"; $sql .= " limit ?"; $sql .= " offset ?"; try { $db = db::getinstance(); $stmt = $db->dbh->prepare($sql); $n = 1; //these must stay in same order match ? placeholders if(isset($args['location'])) $stmt->bindvalue(($n++), $args['location'], pdo::param_int); $stmt->bindvalue(($n++), $limit, pdo::param_int); $stmt->bindvalue(($n++), $offset, pdo::param_int); $result = $stmt->execute(); $stmt->setfetchmode(pdo::fetch_assoc); $rows = array(); if($result !== false) { while($row = $stmt->fetch()) { $rows[] = $row; } $data['comments'] = $rows; return $data; }else { logit('query failed'); return false; } }catch(pdoexception $e) { logit($e->getmessage()); return false; } }
if example wanted {comment_id, user_id, score} associated comments of user 5, query involve inner join , like:
select s.comment_id, s.user_id, s.score commentscore s inner join comment c on c.comment_id = s.comment_id c.user_id = 5
Comments
Post a Comment