2009-04-27 77 views
6

我是PHP/MySQL的新手,并且是CodeIgniter的新手。 我在许多MySQL表中都有信息。我想用JOIN检索它,其中表主键等于$ variable ...我怎样才能得到所有没有主键字段的字段???CodeIgniter/PHP/MySQL:通过JOIN检索数据

我现在正在做的是这样的(只有两个表连接在这里):

function getAll($id) { 

    $this->db->select('*'); 
    $this->db->from('movies'); 
    $this->db->join('posters', 'movies.id= posters.id'); 
    // WHERE id = $id ... goes here somehow... 
    $q = $this->db->get(); 

    if ($q->num_rows() == 1) { 
     $row = $q->row(); 
     $data = array(
       'id' => $row->id, 
       'title' => $row->title, 
       'year' => $row->year, 
       'runtime' => $row->runtime, 
       'plotoutline' => $row->plotoutline, 
       'poster_url' => $row->poster_url 
      ); 
    } 

    $q->free_result(); 
    return $data; 

ID(PK),名称,年份,运行时间和plotoutline从第一表列和poster_url是场从第二张桌子。第二个表格还包含我不想检索的ID(PK)列,因为我已经有了。

回答

21

乔恩是对的。这里有一个例子:

$this->db->select('movies.id, 
        movies.title, 
        movies.year, 
        movies.runtime as totaltime, 
        posters.poster_url'); 
$this->db->from('movies'); 
$this->db->join('posters', 'movies.id= posters.id'); 
$this->db->where('movies.id', $id); 
$q = $this->db->get(); 

这将返回所有的对象 - > ID, - >标题 - >年 - > totalTime和 - > poster_url性能。您将不需要额外的代码来从每一行中获取数据。

不要忘记,如果Active Record的语法变得有点笨重,你可以使用完整的SQL查询,并得到相同的结果:

$sql = "SELECT movies.id, 
     movies.title, 
     movies.year, 
     movies.runtime as totaltime, 
     posters.poster_url 
     FROM movies 
     INNER JOIN posters ON movies.id = posters.id 
     WHERE movies.id = ?" 

return $this->db->query($sql, array($id))->result(); 

这两种形式都将确保您的数据被正确地转义。

CodeIgniter Active Record

Query Binding in CodeIgniter

+0

这样,我将在两个表之间的连接,并得到所有的结果吗?我怎样才能从我想要获取数据的行中指定ID?就像'WHERE movies.id = $ id'.. – Jonathan 2009-04-28 13:42:09

4

星号将返回所有字段。要返回其中的一个子集,即所有字段都与重复的id字段分开,只需列出您需要的列而不是使用'*'。

无论如何不使用星号通常是一个好主意。在应用程序的未来,有人可能会增加一个大的字段到表中,这将超出您的要求,并会减慢您的查询速度。

1

简单地说与方法链接:

$this->db->select('*') 
     ->from('movies') 
     ->join('posters', 'movies.id= posters.id') 
     ->where('movies.id', $id) 
     ->get(); 
0
$this->db->select('*'); 
$this->db->from('blogs'); 
$this->db->join('comments', 'comments.id = blogs.id'); 
$query = $this->db->get();