Question

Following is the query to take all records from page table and respective access_level from role_page_access table, join together by page.id for a given roleid. $roleid is the parameter to this method.

$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';

Actually, I need to use this query for ignited datatables. But at least if I can convert this to active record, that will be very helpful.

Is there a way to just specify regular query in active records? Otherwise how to convert this to active records?

UPDATE: page table has pages and role_page_access table has mapping between userrole and page with an integer field "access_level" to specify have access or not. If there are no mapping also considered as no access.

I want all the records from page and matching access_level from role_page_access by pageid and given role. So there will be null access_level if no matching records found in mapping table.

I have to use this in $this->db or $this->datatables.

No correct solution

OTHER TIPS

You can do it with activerecord like this:

$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';
    }
}

That will join the page table records with the role_page_access table records by the page.id field if it matches, filtered by the role_id you pass along.

You can even do method chaining if you have a supported PHP version, check the reference here.

Update

If you still want to retrieve page records even if that role_id does not have access you just have to set the join as left outer:

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

That'll give ALL pages records, even if they don't match a role on role_page_access and the resultset object will have a NULL value on role_page_access. I updated the original code to show you an example.

Update 2 If you want to filter by role_id but still have the unmatched records:

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

But you will have to filter them by the access_level to check if is NULL cause if it is, it means that there was no matching page for the page_id and the role_id (that you passed as param) combination:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top