get user role by user id in moodle - sql

I want to get user role from user id. I am using loop in my code where i want to show all user except admin. i used below code but its not working.
$context = get_context_instance (CONTEXT_SYSTEM);
$roles = get_user_roles($context, $USER->id, false);
$role = key($roles);
$roleid = $roles[$role]->roleid;
Its provide me blank array as like screenshot. Also below my all code.
https://prnt.sc/gq8p12
$allUsers = $DB->get_records('user');
$SQL = "SELECT * FROM `".$CFG->prefix."config` WHERE `name` LIKE 'siteadmins'";
$getSiteAdmins = $DB->get_record_sql($SQL);
$explodeAdminIds = explode(',', $getSiteAdmins->value);
$context = get_context_instance (CONTEXT_SYSTEM);
if(!empty($allUsers))
{
foreach ($allUsers as $allUser)
{
if(!in_array($allUser->id, $explodeAdminIds))
{
$roles = get_user_roles($context, $allUser->id, false);
$role = key($roles);
$roleid = $roles[$role]->roleid;
echo 'USER ID -- '.$allUser->id.' >>> ';
print_r($roles); echo '<br>';
$name = ''.$allUser->id.'_'.$allUser->firstname.' '.$allUser->lastname.'';
$confirmed = ($allUser->confirmed == 1) ? 'Active' : 'In-active';
$table->data[] = array(
$i,
$name,
'Team Name',
$allUser->email,
$allUser->phone1,
'Role',
$confirmed,
//empty($coachusrarr)?'--':implode(',',$coachusrarr),
//empty($tmpleaderarr)?'--':implode(',',$tmpleaderarr),
//$coach,
);
$i++;
}
}
}

The basic problem is that get_user_roles($context, $userid) will only get you a list of roles assigned at that particular context level. Very few users have roles assigned at the system context, it is much more usual for roles to be assigned at a course level. This allows users to have different roles in different courses (a teacher on one course, might be enrolled as a student on another course).
If you want to get all the roles for a user, then you're going to need to do something like this:
$roleassignments = $DB->get_records('role_assignments', ['userid' => $user->id]);
You can then loop through all the $roleassignments and extract the 'roleid' from them (alternatively, you could use the $DB->get_fieldset command, to extract the roleids directly).
Note also that you should be using context_system::instance() instead of the old get_context_instance(CONTEXT_SYSTEM) (unless you are using a very old and insecure version of Moodle).
For getting the site admins, use get_admins() (or, if you really want to access the config value, use $CFG->siteadmins).

If you want to get a user role for a course by user id then this script will help you.
$context = context_course::instance($COURSE->id);
$roles = get_user_roles($context, $USER->id, true);
$role = key($roles);
$rolename = $roles[$role]->shortname;

Related

Get user data from database codeignter

I have two tables in one database, table one called: ci_admin, and table two called active_ingredient.
I want to get user data from the active_ingredient table where user_id equals admin_id from ci_admin table using the current user session.
this code, get data for all user, I need the data inserted by the user only:
$wh =array();
$SQL ='SELECT * FROM active_ingredient';
$wh[] = "SELECT 1
FROM ci_admin
WHERE ci_admin.admin_id = active_ingredient.user_id";
if(count($wh)>0)
{ $WHERE = implode(' and ',$wh);
return $this->datatable->LoadJson($SQL,$WHERE);
}
else
{
return $this->datatable->LoadJson($SQL);
}
Try this, it will help you.
$this->db->select('ai.*,ca.*');
$this->db->from('active_ingredient ai');
$this->db->join('ci_admin ca', 'ca.admin_id = ai.user_id', 'left');
$this->db->where($data); //pass the session data for exact filter
$query = $this->db->get();
return $query->result();

Odoo XML-RPC: changing the active company?

My Odoo user has access to two companies but when I run code like the following (using ripcord as described here) it only shows me data for the default company:
$domain = [];
$domain[] = ['year', '=', '2019'];
$fields = ['account_id', 'date', 'balance2'];
$groupby = ['account_id', 'date'];
$result = $models->execute_kw($a, $b, $c, 'account.budget.report', 'read_group', [$domain, $fields, $groupby], []);
Adding ['company_id', '=', '31'] to the array $domain doesn't work.
How can I change the company I currently want to work with?
Figured it out myself. Looking at how the browser changes the company I need to do this write operation first:
$result = $models->execute_kw($a, $b, $c, 'res.users', 'write', [[75], ['company_id' => 31]]);
75 is my user ID.

Codeigniter populate nested associations

this is the results i need from the database
{comment: 'hello there', user: [{name: 'sahan', id: 1}], id: 2}
function used to get comments
public function get_comments(){
$query = $this->db->get('comments');
return $query->result_array();
}
I have a comments table and a users table, When a user comments on something the
comment is saved as follows
comment > Comment text
user: userid
So when the data is shown I need codeigniter to populate the user field with the user data found from the users table
Does anyone know how to do this ?
I used this functionality in SailsJS but dont know how to do it here in CodeIG
Sails.js populate nested associations
Codeigniter 's active record is not as advanced as SailJS active record, but you can achieve what you are asking for with two queries within the same method.
I'm assuming the comments table has a foreign key to the users table through a user_id field.
public function get_comments() {
/* Get all the comments */
$query = $this->db->get('comments');
$comments = $query->result_array();
/* Loop through each comment, pulling the associated user from the db */
foreach $comments as &$comment {
$query = $this->db->get_where('users', array('id' => $comment['user_id']));
$user = $query->result_array();
/* Put the user's data in a key called 'user' within the comment array */
$comment['user'] = $user;
/* Remove the unnecessary user_id and $user variable */
unset($comment['user_id']);
unset($user);
}
return $comments;
}

Only join rows that meet certain criteria (left join of data that is left joined)

I have users that have FacebookPage and Application entities associated to them. FacebookPage entities also have Application entities associated with them.
$qb = $this->createQueryBuilder('u')
->addSelect('p', 'a')
->leftJoin('u.facebook_pages', 'p')
->leftJoin('p.applications', 'a')
->leftJoin('a.editors', 'e', 'WITH', 'e = :user')
->where('u = :user')
->setParameter('user', $user)
->orderBy('p.name', $order)
;
$u = $qb->getQuery()->getSingleResult();
return $u->getFacebookPages();
I want to return all of the user's Facebook pages and then show a count of applications associated with that page. I only want to count the applications where the user is an editor.
When run my current query, the pages have a count with all the page's applications (so the count includes applications where the user is not an editor).
If I change the a.editors leftJoin to a join, I get the correct counts for the pages, but it only lists pages that actually have any applications.
How can I show all the pages and only join the applications where the user is an editor?
I solved this by adding a new query to get app ids for the applications where user is an editor.
$user_apps = $this->getEntityManager()->getRepository('Application')->getUserApps($user);
$app_ids = array();
foreach($user_apps as $app) {
$app_ids[] = $app->getId();
}
$qb = $this->createQueryBuilder('u')
->addSelect('p', 'a')
->leftJoin('u.facebook_pages', 'p');
if(count($app_ids)) {
// join with IN statement to include only apps where user is an editor
$qb->leftJoin('p.applications', 'a', 'WITH', sprintf('a.id IN (%s)', implode(',', $app_ids)));
} else {
// join empty anyway to avoid db calls when iterating over pages
$qb->leftJoin('p.applications', 'a');
}
$qb
->where('u = :user')
->setParameter('user', $user)
->orderBy('p.name', $order)
;
try {
$u = $qb->getQuery()->getSingleResult();
} catch (Exception $e) {
throw $e;
}
return $u->getFacebookPages();
This now returns all the user's Facebook pages and only join applications where user is an editor. I am probably going to change this to a DQL query so I can move the ids in IN to a subquery.

Yii: adding custom fields

Is there a simple way of adding custom fields to a model? Say I have a table "user" with 3 fields: id, name and surname. I want this:
$user = User::model()->findByPk(1);
$echo $user->fullName; // echoes name and surname
Please note: I want this custom field to be added via sql, smth like
$c = new CDbCriteria();
$c->select = 'CONCAT("user".name, "user".surname) as fullName';
$user = User::model()->find($c);
Problem is that fullName property is not set.
UPD:
here is the code for a little bit trickier problem -- custom field from another table. This is how it's done:
$model = Application::model();
$model->getMetaData()->columns = array_merge($model->getMetaData()->columns, array('fullName' => 'CONCAT("u".name, "u".surname)'));
$c = new CDbCriteria();
$c->select = 'CONCAT("u".name, "u".surname) as fullName';
$c->join = ' left join "user" "u" on "t".responsible_manager_id = "u".id';
$model->getDbCriteria()->mergeWith($c);
foreach ($model->findAll() as $o) {
echo '<pre>';
print_r($o->fullName);
echo '</pre>';
}
You can add a function to the User class:
public function getFullName() { return $this->name.' '.$this->surname; }
This will return the full name as if it were an attribute from the database. This is much easier than adding a calculated column to the SQL.
In model
public function getMetaData(){
$data = parent::getMetaData();
$data->columns['fullName'] = array('name' => 'fullName');
return $data;
}
Thus not recommended