2017-05-23 29 views
0

我有這樣的PHP代碼來獲取使用PHP MVC的評論,但我必須使用URL來獲取URL ID,並選擇發佈和評論的URL ID :如何獲取文章和評論沒有Id在Url使用Php

網址ID:http://localhost/blogs/my-article-title/12

代碼在我的控制器是這樣的:

public function index($title, $id)` 
    { 
     $post = $this->load->model('Posts')->getPostWithComments($id); 
} 

而在我的模型是這樣的:

public function getPostWithComments($id) 
    { 
     $post = $this->select('p.*', 'c.name AS `category`', 'u.first_name', 'u.last_name', 'u.image AS userImage') 
        ->from('posts p') 
        ->join('LEFT JOIN categories c ON p.category_id=c.id') 
        ->join('LEFT JOIN users u ON p.user_id=u.id') 
        ->where('p.id=? AND p.status=?', $id, 'enabled') 
        ->fetch(); 

     if (! $post) return 

     $post->comments = $this->select('c.*', 'u.first_name', 'u.last_name', 'u.image AS userImage') 
           ->from('comments c') 
           ->join('LEFT JOIN users u ON c.user_id=u.id') 
           ->where('c.post_id=?', $id) 
           ->fetchAll(); 

     return $post; 
    } 

上面的代碼用於當我想在文章頁面上看到文章和評論,但我很困惑,如何獲得一篇文章的評論,而無需使用現有url的id,我的意思是當我想要直接在展會上打開網站的主頁,帖子和評論。

我試圖做到這一點我控制器上:

public function index() 
    { 
     $post = $this->load->model('Posts')->getPostWithComments(); 
    } 

,這在我的模型,但我得到的所有崗位,而不是對所有的意見,我在那裏有一個錯誤:

我的模型:

public function getPostWithComments() 
    { 
     $post = $this->select('p.*', 'c.name AS `category`', 'u.first_name', 'u.last_name', 'u.image AS userImage') 
        ->from('posts p') 
        ->join('LEFT JOIN categories c ON p.category_id=c.id') 
        ->join('LEFT JOIN users u ON p.user_id=u.id') 
        ->fetchAll(); 

     if (! $post) return null; 

     $post->comments = $this->select('c.*', 'u.first_name', 'u.last_name', 'u.image AS userImage') 
           ->from('comments c') 
           ->join('LEFT JOIN users u ON c.user_id=u.id') 
           ->fetchAll(); 
     return $post; 
    } 

有人可以幫助我來顯示所有帖子和所有COMENT在我的PHP代碼中的每個帖子,而無需使用URL ID?

在此先感謝

回答

0

你需要的是首先從數據庫中獲取所有的職位URL ID,然後打電話給你getPostWithComments($id)在每個鏈接的id。 例如:

$urls = array(**an array containing urls gotten from DB**); 
$posts = array(); //initialize an empty array so we can store the posts here 
foreach($urls as $url) { 
    $posts[] = load->model('Posts')->getPostWithComments($url); 
} 

現在你可以通過$posts集成和訪問每個崗位。

+0

我的意思是,我可以做什麼來顯示張貼評論在我的主頁沒有網址ID。像這樣的'getPostWithComments($ id)'正常,但我的意思是,如何獲得張貼評論,但不使用像這樣的網址id getPostWithComments()。先謝謝你的迴應。 –

+0

當請求方法爲GET時,將使用url id。如果你不想在url中顯示,你可以使用請求方法POST,但我認爲這不是正確的約定。無論如何,首先你如何選擇這些特定的帖子在主頁上顯示?你只是在表格中顯示最後一個帖子ID嗎? – JMS786

+0

我想如果你再次閱讀我的答案,你會發現我回答了你的問題。首先從數據庫中選擇所有ID,然後將它們傳遞給'getPostWithComments($ id)'並將結果保存在一個數組中,然後迭代該數組並在主頁上顯示數據。 – styl3r

相關問題