Codeigniter joined tables getting wrong output

岁酱吖の 提交于 2019-12-24 03:30:03

问题


I'm having an function which gets data from my database, and joins different tables. This is the method:

public function getCallcenterCall() {
    $this->db->select('bedrijf.*, status.status_naam, quickscan.datum_verzonden');
    $this->db->join('quickscan', 'bedrijf.id = quickscan.bedrijf_id');
    $this->db->join('status', 'bedrijf.status = status.status_id');
    $this->db->where('status', '0');

    $query = $this->db->get('bedrijf');

    return $query->num_rows() > 0 ? $query-> result_array() : FALSE;
}

In the table status I got 3 rows: 'id', 'status_id', 'status_naam'. In my view, I output the status_naam, but here it gets wrong.

Instead of giving me the 'status_naam' that belongs to 'status_id=0'; it gives me the 'status_naam' where 'status_id=1'.

The same thing happens if I try to get the 'status_naam' for 'status_id=1' then it gives me the 'status_naam' from 'status_id=2'.

What am I doing wrong? Thanks in advance!


回答1:


Is your database setup to use foreign key constraints?

simple example :

Tables

create table `groups`(
`id` int(10) unsigned not null auto_increment primary key,
`name` varchar(30) not null,
`colour` varchar(7) not null,
`created_at` datetime not null,
`updated_at` datetime not null
 )engine=innodb;


create table `users`(
`id` int(10) unsigned not null auto_increment primary key,
`group_id` int(10) unsigned not null,
`permissions` varchar(255) not null default '{[u, r, d]}',
`created_at` datetime not null,
`updated_at` datetime not null,
index(group_id),
foreign key(group_id) references groups(id)
)engine=innodb;

Raw SQL

select g.name, u.permissions from users as u
left join groups as g
on g.id = u.group_id
where id=1

As you can see you set an index of group_id on the users table, then set it as our foreign key and tell it to reference the groups id.

innodb engine is required & the rows must match identically.

...hope that makes sense




回答2:


I think you might need to use the third parameter of join, e.g.

$this->db->join('quickscan', 'bedrijf.id = quickscan.bedrijf_id', 'inner');
$this->db->join('status', 'bedrijf.status = status.status_id', 'inner');


If that still fails, you might have to go with a custom query instead:

$s  = 'SELECT ';
$s .=    'bedrijf.*, status.status_naam, quickscan.datum_verzonden ';
$s .= 'FROM bedrijf ';
$s .= 'INNER JOIN quickscan ON bedrijf.id = quickscan.bedrijf_id ';
$s .= 'INNER JOIN status ON bedrijf.status = status.status_id ';
$s .= 'WHERE (status = ?)';

$query = $this->db->query($s, array('0'));



回答3:


Have you tried using the from method?

$this->db->select...
$this->db->from('bedrijf')
...
$query = $this->db->get()
...


来源:https://stackoverflow.com/questions/8534226/codeigniter-joined-tables-getting-wrong-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!