【发布时间】:2016-05-23 17:31:55
【问题描述】:
我有 3 个表,即 - celebs、celeb_roles、celeb_industry。celebs 是与其他 2 个表具有一对多关系的主表。
celebs 有列 -
身份证、姓名、国籍、身份。
celebs_roles 有列 -
id, celeb_id, role_id。
celebs_industry 有列 -
id、celeb_id、industry_id。
角色和行业的数量有限且固定。所以我把它们放在一个带有id=>value 对的配置文件中。所以如果我从结果中得到role_id,我可以从配置文件中获取值。 industry_id 也是如此。
现在为了从一个给定的 id 获取名人详细信息,我在模型中编写了如下查询。
public function getCelebSingle($celebId)
{
$this->db->select('*');
$this->db->from('celebs');
$this->db->join('celebs_roles', 'celebs_roles.celeb_id = celebs.id');
$this->db->join('celebs_industry', 'celebs_industry.celeb_id = celebs.id');
$this->db->where('celebs_roles.celeb_id', $celebId);
$this->db->where('celebs_industry.celeb_id', $celebId);
$query = $this->db->get();
return $query->result_array();
}
在数据库中,celebs 中有一条记录,相同的 celeb_id 在其他 2 个表中各有 2 条记录。
我得到的结果如下。
Array
(
[0] => Array
(
[id] => 1
[name] => new test
[nationality] => whatever
[status] => Pending
[celeb_id] => 1
[role_id] => 1
[industry_id] => 1
)
[1] => Array
(
[id] => 1
[name] => new test
[nationality] => whatever
[status] => Pending
[celeb_id] => 1
[role_id] => 3
[industry_id] => 1
)
[2] => Array
(
[id] => 2
[name] => new test
[nationality] => whatever
[status] => Pending
[celeb_id] => 1
[role_id] => 1
[industry_id] => 2
)
[3] => Array
(
[id] => 2
[name] => new test
[nationality] => whatever
[status] => Pending
[celeb_id] => 1
[role_id] => 3
[industry_id] => 2
)
)
所以对于celebs 表中只有一条记录,我需要将它放在一个循环中,我认为这有点过载。如果其他 2 个表中的记录数增加,则结果数组中的项目也会增加。所以我想知道,我能得到类似下面的结果吗?
Array
(
[0] => Array
(
[id] => 1
[name] => new test
[nationality] => whatever
[status] => Pending
[celeb_roles] => array(
[0] => Array
(
[id] => 1
[celeb_id] => 1
[role_id] => 1
)
[0] => Array
(
[id] => 1
[celeb_id] => 1
[role_id] => 2
)
)
[celeb_industry] => array(
[0] => Array
(
[id] => 1
[celeb_id] => 1
[industry_id] => 1
)
[0] => Array
(
[id] => 1
[celeb_id] => 1
[industry_id] => 2
)
)
)
)
这只是结果数组的一个期望,但我不知道如何实现这个结果数组。有人可以看看吗?
这是一个可能的重复 - Codeigniter group by and create multidimensional array 。但答案并不令人满意。答案明确指出不要使用 JOIN,而是使用普通的 Codeigniter 获取查询,我认为这会导致 3 个问题的查询。如果我选择 celebs 表的所有记录怎么办?然后,查询数将是 3 * Number of records in celebs table ,这将超载。如果没有其他办法,我只能这样做,但我希望有更好的方法来做到这一点。
【问题讨论】:
标签: database codeigniter model