I'm new to Laravel and MySQL, i couldn't figure out how to use a single join query to get user, their posts, and post comments. I'm not sure if i'm doing it right, but there must be a better way to fetch posts and post comments in a structured way. This is what I've done so far. I'm using $username to lookout for every single post user has made in Posts table and then looping through each post to see if that specific post has any comments with post.id.
It's working perfectly, but i feel that it's a bit expensive way to loop through each single posts to find it's comments with an individual query. Is there a better way to do it in a single query and keep data structured so that i can easily populate my view?
public function user($username){
$user = User::where('username',$username);
if($user->count()){
$user = $user->first();
$posts = Posts::where('username', $username)->orderBy('created_at', 'DESC')->orderBy('at','DESC')->paginate(4);
if(count($posts)>0){
$i=0;
foreach($posts as $data){
$ago = date('Y-m-d', strtotime($data->created_at)).' '.$data->at;
$comments = Comments::where('post_id',$posts[$i]->id)->get();
$posts[$i]->at = ProfileController::getElapsedTime($ago);
$posts[$i]->comments = $comments;
$j=0;
foreach($posts[$i]->comments as $comments){
$c_time = date('Y-m-d', strtotime($comments->created_at)).' '.$comments->at;
$posts[$i]->comments[$j]->at = ProfileController::getElapsedTime($c_time);
$comment_user = User::where('username', $posts[$i]->comments[$j]->comment_user)->first();
$posts[$i]->comments[$j]->user_dp = $comment_user->dp_uri;
$posts[$i]->comments[$j]->name = $comment_user->name;
$j++;
}
//echo $posts[$i]->comments.'<br><br>';
$i++;
}
}
return View::make('profile.posts')
->with('user',$user)->with('posts', $posts);
}else{
return Response::view('errors.missing', array(), 404);
}
}
Related
I have an array of CSV values in my Database like category1[obj1,obj2,obj3..]
View
<?php echo $row_company->category1;?>
Controller
$row_company = $this->employers_model->get_company_details_by_slug($company_name);
The employers_model then calls a procedure which in turn executes the required query which displays the contents of row = category1 in this fashion,
obj1,obj2,obj3...
I want to be able to show this result without the commas and as a list like this
obj1
obj2
obj3..
I'm Using CodeIgniter MVC Framework, I have some vague idea about the uses of implode function, and came across preg_split too, But don't know where to start meddling around from, the view or the controller.
Any direction towards the solution would be appreciated.
Edit : row_company in detail.
$row_company = $this->employers_model->get_company_details_by_slug($company_name);
if(!$row_company){
redirect(base_url(),'');
exit;
}
$company_website = ($row_company->company_website!='')?validate_company_url($row_company->company_website):'';
$data['row_company'] = $row_company;
$data['company_logo'] = $company_logo;
$data['company_join'] = $company_join;
$data['company_website'] = $company_website;
$data['company_location'] = $company_location;
$data['title'] = $row_company->company_name.' jobs in '.$row_company->city;
$this->load->view('company_view',$data);
}
employers_model content
public function get_company_details_by_slug($slug) {
$Q = $this->db->query('CALL get_company_by_slug("'.$slug.'")');
if ($Q->num_rows > 0) {
$return = $Q->row();
} else {
$return = 0;
}
$Q->next_result();
$Q->free_result();
return $return;
}
the procedure itself get_company_details_by_slug
BEGIN
SELECT emp.ID AS empID, emp.sts1, pc.ID, emp.country, emp.city, pc.company_name, pc.company_description, pc.company_location, pc.company_website, pc.no_of_employees, pc.established_in, pc.company_logo, pc.company_slug, pc.category1, pc.category2, pc.category3, pc.company_join
FROM `pp_employers` AS emp
INNER JOIN pp_companies AS pc
WHERE pc.company_slug=slug AND emp.sts1 ='active';END
Figured it out after referring many codeigniter/php forums.
Pretty simple actually,
<?php $array = explode(',', $row_company->category1);
foreach ($array as $item)
{
echo "<li>$item</li>";
}
?>
Thank you Nigel for pointing out to use explode function.
Cheers
In symfony and Doctrine i am using the session to save a query result then later on i am filtering this result with some parameters.
The problem is that once the parameters are changed i can't get the original results set. Here is the code
fetching results and saving to session
$query = $this->getDoctrine()->getManager()->createQueryBuilder();
$query->select("sp")
->from("CoreBundle:ServiceProvider","sp")
->innerJoin("sp.offers","offer")
->innerJoin("offer.service","service","with","offer.service = service")
->innerJoin("sp.firstImage","fi")
->andWhere("sp.city = :city_name")->setParameter("city_name",$cityName)
->orderBy("sp.points" ,"DESC")
->addOrderBy("sp.name" ,"ASC");
$queryAndFilters = $this->getFilters($query,$postData);
$query = $queryAndFilters['query'];
$filters=$queryAndFilters['filters'];
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$query, /* query NOT result */
$pageNumber,
20/*limit per page*/
);
$query = $query->getQuery();
$query->setHint(\Doctrine\ORM\Query::HINT_INCLUDE_META_COLUMNS, true);
$this->get('session')->set("results",$query->getResult());
and then in another function
filtering the results
$results = $this->get('session')->get("results");
$filteredResults = array();
// print_r(array_keys($results[0]));
foreach($results as $result){
$sp = $result;
foreach($sp->getOffers() as $offer){
// echo "found offer ".$offer->getName()." with price ".$offer->getPrice()."<br />";
$sp->removeOffer($offer);
if($offer->getPrice() < $minPrice || $offer->getPrice() > $maxPrice){
}else{
$sp->addOffer($offer);
// echo 'added $offer '.$offer->getName()." with price : ".$offer->getPrice()."<br />";
}
if(sizeof($sp->getOffers()) > 0 ){
array_push($filteredResults,$sp);
}
}
}
the first time i change the $minPrice and $maxPrice variables the results are filtered right and exactly what i need
but after raising the $maxPrice again the high prices are not being added to the $filteredResults
i tried also to assign $offer and $result to new variables but still not working
any idea how to fix this ?
ps. i can't change the query or to fetch them already with the query.
When you save entities in the session this entities are serialized with the values that actual at the serialization moment. Next changes of entities are not affect the stored values if you don't rewrite them in the session.
Also entitiy serializing has some limitations on private properties.
I can list the users that have relations of a current user, but how do I list users that don't have relations with the current user. Or how do I exclude users that have relations with the current user from a list. I am happy to see it in javascript, ios etc..
$user = ParseUser::getCurrentUser();
$relation = $user->getRelation("follow");
$usersFollowed = $relation->getQuery()->find();
print_r($usersFollowed);
Thanks
I'm not using php, but you could try to use notEqualTo constraint to 'follow' with current user.
Something like query.notEqualTo('follow', Parse.User.current()); in js
I have found a work around to achieve what I wanted to achieve. I am happy for others to improve it.
$user = ParseUser::getCurrentUser();
$relation = $user->getRelation("follow");
$usersFollowed = $relation->getQuery()->find();
// loop through all the users that are being followed
for ($i = 0; $i < count($usersFollowed); $i++) {
$object = $usersFollowed[$i];
$usernames = $object->get('username');
// concatenate the usernames to produce a string
$str_usernames .= $usernames . ' ';
}
// convert the string into an array
$array_usernames = explode(" ", $str_usernames);
print_r($array_usernames);
echo "<br><br>";
// query all the usernames not contained in the above array
$query = new ParseQuery("_User");
$query->notContainedIn("username", $array_usernames);
$results = $query->find();
print_r($results);
I hope this helps others, it costs two api requests. I am not sure how it would perform over thousands or hundreds of thousands of usernames though.
Hello i'm trying to make a post count function based on the codeigniter framework and what i done so far works great looking by my side. The function is complete and everything works fine.
But i have a question here from some experts to tell me that this is the correct ussage of the function and non of the above will harm my page loading. The function is accesed by jQuery get function on every click on the post.
First i'm checking if there is an ip address and if the ip address date inserted is more then 24 hours if its more i'm deleting the current row and then checking again becuase of the previous select its still remembering the last ip address and inserting again with new datime.
And other question should i make cleanjob every week or similar for all ip addreses ?
Here is my code:
function show_count($post_id){
$ip = $this->input->ip_address();
$this->db->select('ip_address,data');
$this->db->from('post_views');
$this->db->where('ip_address',$ip);
$query = $this->db->get();
foreach ($query->result() as $row){
$ip_address = $row->ip_address;
$data = $row->data;
}
if(isset($ip_address) && time() >= strtotime($data) + 8640){
$this->db->where('ip_address',$ip);
$this->db->delete('post_views');
}
$this->db->select('ip_address');
$this->db->from('post_views');
$this->db->where('ip_address',$ip);
$query = $this->db->get();
foreach ($query->result() as $row){
$ip_address_new = $row->ip_address;
}
if(!isset($ip_address_new) && $ip_address_new == false){
$date = new DateTime('now', new DateTimeZone('Europe/Skopje'));
$this->db->set('views', 'views+ 1', false);
$this->db->where('post_id',$post_id);
$this->db->update('posts');
$data = array(
'ip_address'=>$ip,
'data'=>$date->format("Y-m-d H:i:s")
);
$this->db->insert('post_views',$data);
}
}
Thanks, any suggestions will be appreciate.
Instead of doing lots of queries to increment unique views on your posts, you should use and set cookies and have a fallback method if cookies are not enabled.
$post_id = "???"
if(isset($_COOKIE['read_articles'])) {
//grab the JSON encoded data from the cookie and decode into PHP Array
$read_articles = json_decode($_COOKIE['read_articles'], true);
if(isset($read_articles[$post_id]) AND $read_articles[$post_id] == 1) {
//this post has already been read
} else {
//increment the post view count by 1 using update queries
$read_articles[$post_id] = 1;
//set the cookie again with the new article ID set to 1
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}
} else {
//hasn't read an article in 24 hours?
//increment the post view count
$read_articles = Array();
$read_articles[$post_id] = 1;
setcookie("read_articles",json_encode($read_articles),time()+60*60*24);
}
I am testing out the Redbean ORM. I like how it works, less work for me :) I am using the redbean books example, from their website. I have been able to create new books with authors and titles, and display them to the page with no problem. I added another dimension to learn how to link pages to my books.
I am able to add an entry into the book table, as well as add an entry into the page table using the following code:
----------- dbmgmt.php ---------------------------------
function AddNewBook($FORMINFO){
$newBook = R::dispense('book');
$newBook->title = $FORMINFO['title'];
$newBook->author = $FORMINFO['author'];
$newBook->create_date = R::isoDateTime();
$newPage = R::dispense('page');
$newPage->pagetext = $FORMINFO['pagetext'];
$newBook->ownPage = $newPage;
$id = R::store($newBook);
return R::load('book', $id);
}
Both tables show the proper entries (new ids and populated fields). However, I am having a hard time accessing the pagetext field from the page table. This is the code I have been using for that:
----------- dbmgmt.php ---------------------------------
function GetBooks($id){
if($id == ""){
return R::find('book');
}
else{
return R::find('book','id = ?', array($id));
}
}
----------- GetBooks.php ---------------------------------
$id = "";
if(isset($_GET['id'])){
$id = $_GET['id'];
}
$books = GetBooks($id);
$booklist = "";
foreach($books as $book){
$pagetext = "";
foreach($book->ownPage as $page){
$pagetext .= $page->pagetext; //Errors with "Notice: Trying to get property of non-object"
}
$booklist .= "<tr id='$book->id'><td><a class='linkEdit' href='edit.php?id=$book->id'><img src='http://cdn1.iconfinder.com/data/icons/ledicons/page_white_edit.png' /></a> <span class='book-title'>$book->title</span></td><td><span class='book-author'>$book->author</span></td><td><span class='page-text'>$pagetext</span></td></tr>";
}
echo $booklist;
------------------------------------------------------------
When I print_r($book->ownPage), I don't even see the page entry that I can clearly see in the page table via phpmyadmin. I have tried many different ways of accessing the pagetext field via my script above, but can't get anywhere with it.
Any insight would be most welcome. Otherwise I will have to try a different, albeit bigger and more cumbersome, ORM.
Thanks in advance.
I am not 100% sure as I haven't encountered this problem yet myself, but I am almost positive, $book->ownPage needs to be an array:
$newPage = R::dispense('page');
$newPage->pagetext = $FORMINFO['pagetext'];
$newBook->ownPage[] = $newPage;
$id = R::store($newBook);