gpt4 book ai didi

php - CodeIgniter Active Record 或 Ignited 数据表中的复杂查询

转载 作者:行者123 更新时间:2023-11-30 23:05:22 24 4
gpt4 key购买 nike

以下是从页表中获取所有记录和从 role_page_access 表中获取相应 access_level 的查询,通过 page.id 将给定的 roleid 连接在一起。 $roleid 是此方法的参数。

$query = 'select p.*,t.access_level from page p '.
'left join (SELECT p.id,rpa.role_id,rpa.access_level FROM page p '.
'left join role_page_access rpa on rpa.page_id = p.id '.
'where rpa.role_id = ' . $roleid . ') as t on p.id = t.id';

实际上,我需要将此查询用于点燃的数据表。但至少如果我可以将其转换为事件记录,那将非常有帮助。

有没有办法只在事件记录中指定常规查询?否则如何将其转换为事件记录?

更新:页表有页面,role_page_access 表有用户角色和页面之间的映射,带有整数字段“access_level”以指定是否具有访问权限。如果没有映射也视为没有权限。

我想要 page 中的所有记录,并通过 pageid 和给定的角色匹配 role_page_access 中的 access_level。所以如果在映射表中找不到匹配的记录,则 access_level 为空。

我必须在 $this->db$this->datatables 中使用它。

最佳答案

你可以像这样用 activerecord 来做:

$this->-db->select('page.*,role_page_Access.access_level');
$this->db->from('page');
$this->db->join('role_page_access', 'role_page_access.page_id = page.id', 'left outer');
$this->db->where('role_page_access.role_id', $role_id);

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

foreach($query->result() as $row) {
if(empty($row->access_level)) {
echo 'Role does not have access';
} else {
echo 'Role has access';
}
}

如果匹配,将通过 page.id 字段将 page 表记录与 role_page_access 表记录连接起来,由 role_id 你传递过来。

如果您有受支持的 PHP 版本,您甚至可以进行方法链接,查看引用资料 here .

更新

如果即使该 role_id 没有访问权限您仍想检索页面记录,您只需将连接设置为左外连接:

$this->db->join('role_page_access', 'role_page_access.page_id', 'left outer');

这将提供所有页面记录,即使它们与 role_page_access 上的角色不匹配,结果集对象将在 role_page_access 上具有 NULL。我更新了原始代码以向您展示示例。

更新 2如果您想按 role_id 过滤但仍然有不匹配的记录:

$this->db->where('role_page_access.role_id', $role_id);
$this->db->or_where('role_page_access.role_id', NULL);

但您必须通过 access_level 过滤它们以检查是否为 NULL 因为如果是,则意味着没有与 匹配的页面page_idrole_id(您作为参数传递的)组合:

关于php - CodeIgniter Active Record 或 Ignited 数据表中的复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22154309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com