Codeigniter活动记录:如何读取连接表

时间:2012-10-16 01:02:07

标签: php codeigniter activerecord

我有一些桌子,关系就像这样

img

我希望获得这两张桌子的所有记录。所以我在我的模型中使用这个查询

 $this->db->select('*');
    $this->db->from('ms_Kategori_Material.*,ms_Material_Jasa.*');
    $this->db->join('ms_Material_Jasa', 'ms_Kategori_Material.Kode_Kategori_Material_Jasa = ms_Material_Jasa.Kode_Kategori_Material_Jasa');
    $result = $this->db->get();

    $table = $this->db->get();
    return $table;

然后我收到了错误

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*, `ms_Material_Jasa`.*) JOIN `ms_Material_Jasa` ON `ms_Kategori_Material`.`Kode' at line 2

SELECT * FROM (`ms_Kategori_Material`.*, `ms_Material_Jasa`.*) JOIN `ms_Material_Jasa` ON `ms_Kategori_Material`.`Kode_Kategori_Material_Jasa` = `ms_Material_Jasa`.`Kode_Kategori_Material_Jasa`

为什么我无法读取所需的表格?

3 个答案:

答案 0 :(得分:1)

在你的,你应该没有。*,

    $this->db->from('ms_Kategori_Material','ms_Material_Jasa');

如果您要添加要加入的表,则无需将其添加到。

所以它变成了

 $this->db->from('ms_Kategori_Material');
 $this->db->join('ms_Material_Jasa','....');

最终查询:

 $this->db->select('*');
    $this->db->from('ms_Kategori_Material');
    $this->db->join('ms_Material_Jasa', 'ms_Kategori_Material.Kode_Kategori_Material_Jasa = ms_Material_Jasa.Kode_Kategori_Material_Jasa');
    $result = $this->db->get();

    $table = $this->db->get();
    return $table;

答案 1 :(得分:0)

$this->db->select('*');
$this->db->from('ms_Kategori_Material'); // full table name
$this->db->join('ms_Material_Jasa', 'ms_Kategori_Material.Kode_Kategori_Material_Jasa = ms_Material_Jasa.Kode_Kategori_Material_Jasa');

$result = $this->db->get();
//print_r($this->db->last_query()); display raw sql

$print_r($result->result_array());

了解更多@ http://codeigniter.com/user_guide/database/active_record.html

答案 2 :(得分:0)

你可以尝试这个(加入并从两个表中选择字段)

$this->db->select('ms_Kategori_Material.*, ms_Material_Jasa.*');
$this->db->from('ms_Kategori_Material');
$this->db->from('ms_Material_Jasa');
$this->db->join('ms_Material_Jasa', 'ms_Kategori_Material.Kode_Kategori_Material_Jasa = ms_Material_Jasa.Kode_Kategori_Material_Jasa');
$table = $this->db->get();
return $table->result();