Codeigniter populate nested associations - sql

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

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();

Laravel/SQL: How to fetch data from multiple table in a single query? that too using 'where'

Working on a search functionality on Laravel App(Blog/Posts).
There are multiple types of posts (each having a separate table in the database)
Like Business posts, Social Life posts etc..
Below is the search function on SearchController
class SearchController extends Controller
{
public function search(Request $request, $query = null)
{
if($query == null)
return redirect()->route('home');
$search = Business::where([['title','like','%'.$query.'%'],['status','=',1]])
->orWhere([['description','like','%'.$query.'%'],['status','=',1]])
->paginate(10);
return view('front.search',[
'results' => $search,
'query' => $query
]);
}
}
So basically my question is how to add other types of Post's table also?
My main motive is that when someone searches for anything, the result should be fetched from all types of posts table(business, nature, life & so on..).
You have to maintain common id in both the table
NOTE: Join is the preferable method
$querys = DB::table('Business')->where([['Business.title','like','%'.$query.'%'],['Business.status','=',1]])
->orWhere([['Business.description','like','%'.$query.'%'],['Business.status','=',1]]);
$querys->join('socialtable','socialtable.userid','=','Business.userid');
// Just join the social table
$querys->where('socialtable.title', 'like','%'.$query.'%');
$result = $querys->paginate(10);
If you have a model called Book, like this:
class Book extends Model
{
/**
* Get the author that wrote the book.
*/
public function author()
{
return $this->belongsTo('App\Author');
}
}
Then you can retrieve all of your books with authors like this:
$books = App\Book::with(['author'])->get();
Check out Eager loading from Laravel documentation.
Just add table name before every field
$querys = DB::table('Business')->where([['Business.title','like','%'.$query.'%'],['Business.status','=',1]])
->orWhere([['Business.description','like','%'.$query.'%'],['Business.status','=',1]]);
$querys->join('socialtable','socialtable.userid','=','Business.userid');
// Just join the social table
$querys->where('socialtable.title', 'like','%'.$query.'%');
$result = $querys->paginate(10);

get user role by user id in moodle

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;

Finding an entity that contain only some others entities

I have an association like this :
Chatroom >----< User
So a Chatroom can contains multiple users, and a User can belong to multiple Chatrooms.
Now I want to select all the chatrooms that contains a couple of user, and only this couple.
I tried some solutions, like this one :
public function findByUsers($firstUser, $secondUser){
$qb = $this->createQueryBuilder('c');
$qb
->select('c')
->where('c.users LIKE :firstUser')
->andwhere('c.users LIKE :secondUser')
->setParameters(array(
'firstUser' => $firstUser,
'secondUser' => $secondUser
));
return $qb->getQuery()->getResult();
}
But It doesn't work and return me that kind of error :
[Semantical Error] line 0, col 52 near 'users LIKE :firstUser': Error: Invalid PathExpression. Must be a StateFieldPathExpression.
Some users encountering this error resolved it by adding IDENTITY before the query selector, but I don't understand how to apply it in my case.
So, did someone know how I can get all the chatrooms containing my couple of users ?
Thanks a lot !
EDIT : Adding the doctrine relation annotations
User.php
/**
*
* #ORM\ManyToMany(targetEntity="Chatroom", inversedBy="users")
* #ORM\JoinTable(name="chatrooms_users",
* joinColumns={#ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={#ORM\JoinColumn(name="chatroom_id", referencedColumnName="id")}
* )
*/
private $chatrooms;
Chatroom.php :
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="chatrooms")
*/
private $users;
My final solution was :
public function findByUsers($ids)
{
$count = count($ids);
$qb = $this->createQueryBuilder('chatroom');
$qb->select('chatroom')
->join('chatroom.users', 'u')
->addSelect('COUNT(u) AS HIDDEN ucount')
->groupBy('chatroom.id')
->having('ucount = :count')
->setParameter('count', $count);
foreach ($ids as $key => $id) {
$qb->andWhere(':id' . $key . ' MEMBER OF chatroom.users')
->setParameter('id'.$key, (int) $id);
}
return $qb->getQuery()->getOneOrNullResult();
}
Pass an array of users id (or simply users with some modifications), and the function returns the list of chatrooms that contains only these users

CRUD very slow with conditions, is there any other faster way?

im having problem with CRUd now that i filled the database. CRUD is taking ages to show, becouse it takes condition from M:M tables.
Tables:
Table USER. has many labels (hasMany)
Table LABLE, has many users (hasMany)
Intermidiate Table UserLabel, has two hasOne
I want to show all users from some label with CRUD like this:
MODEL USER:
class Model_User extends Model_Table {
public $table ='user';
function init(){
parent::init();
$this->addField('fbid')->mandatory('Facebook id required');
...
$this->hasOne('Application');
$this->hasMany('UserLabel');
$this->addExpression('ratio')->set(function($model,$select){
return $select->expr('ROUND(([f2] / [f1]) * 100,0)')
->setCustom('f1',$model->getElement('sends'))
->setCustom('f2',$model->getElement('clicked'));
});
$this->addHook('beforeSave',function($m){
$m['updated']=$m->dsql()->expr('now()');
});
}
MODEL LABEL:
class Model_Label extends Model_Table {
public $table ='label';
function init(){
parent::init();
$this->addField('name')->mandatory('Name required');
$this->addFIeld('application_id')->refModel('Model_Application')->defaultValue($this->api->recall('app'))->system(true);
$this->addField('active')->type('boolean')->defaultValue('true')->system(true);
$this->addField('created')->type('timestamp')->defaultValue($this->dsql()->expr('now()'))->system(true);
$this->addField('updated')->type('timestamp')->system(true);
$this->hasMany('UserLabel');
$m = $this->add("Model_UserLabel");
$this->addExpression("users", $m->dsql()
->field($m->dsql()->expr("count(*)"), "all users")
->where("label_id", $this->getField("id"))
);
MODEL USER LABEL
class Model_UserLabel extends Model_Table {
public $table ='userlabel';
function init(){
parent::init();
$this->hasOne('User');
$this->hasOne('Label');
}
}
CODE FOR CRUD
$c = $this->add('CRUD');
$c->setModel('User', array('name', 'gender','country','city'));
$c->model->addCondition('id','in',
$this->add('Model_UserLabel')->addCondition('label_id', $_GET['l'])->dsql()->field('user_id')
);
Is there any better way to do this?
ps. I tested this solution, it is a lot faster but still very slow at around > 5.000 users:
//get all users
$records = $this->api->db->dsql()->option('distinct')->table('user')->join('userlabel.user_id')->field('user.id')->where('userlabel.label_id',$_GET['l'])->do_getAll();
foreach($records as $record){
$users .= ','.$record['id'];
}
//create CRUD
$c = $this->add('CRUD');
$c->setModel('User', array('name', 'gender','country','city','sends','clicked','ratio'));
$c->model->addCondition("application_id", $this->api->recall('app'));
$c->model->addCondition('id','in',
'('.$users.')'
);
Source code express more than words, so you better add your model definition source code (maybe not full) in your question.
What should be one row in your CRUD/Grid? I guess it's not 1 user = 1 row, but 1 user_label should be one row in grid. So you should set UserLabel model as model for your grid.
And then define some additional fields in Model_UserLabel by joining them from user and/or label tables directly like this:
class Model_UserLabel extends SQL_Model {
function init() {
parent::init();
// ...
// fields from user table
$join_u = $this->join('user', 'user_id');
$join_u->addField('username'); // this adds fields in current model from joined table
$join_u->addField('email');
// fields from label table
$join_l = $this->join('label', 'label_id');
$join_l->addField('name');
}
}
Note: source code above is untested and put here only as example.
EDIT:
Try this solution - almost the same as I wrote earlier above:
MODEL USER LABEL
class Model_UserLabel extends Model_Table {
public $table ='userlabel';
function init(){
parent::init();
$this->hasOne('User');
$this->hasOne('Label');
// join user table and add fields to this model from joined user table
$j = $this->join('user', 'user_id');
$j->addField('name');
$j->addField('gender');
$j->addField('country');
$j->addField('city');
}
}
CODE FOR CRUD
$m = $this->add('Model_UserLabel'); // UserLabel here not User
$m->addCondition('label_id', $_GET['l']); // and then this is simple
$c = $this->add('CRUD');
$c->setModel($m, array('name', 'gender','country','city'));
Try this solution and as (almost) always - code is untested.
EDIT:
Please try this version - is it working faster? That's basically your P.S. example, but you shouldn't extract all user IDs, join them and then create huge select with a lot of 'in'.
Faster result should be if you could do all with just one DB request without any additional processing of data.
// parameters
$app_id = $this->api->recall('app);
$label_id = $_GET['l'];
// prepare model for grid
$m = $this->add('Model_User'); // default User model
$m->_dsql()->option('distinct') // add join to userlabel table + conditions
->join('userlabel.user_id')
->where('userlabel.label_id', $label_id)
->where($m->getField('application_id'), $app_id);
// create CRUD and set it's model. All conditions already set on model above
$c = $this->add('CRUD');
$c->setModel($m, array('name', 'gender','country','city','sends','clicked','ratio'));
NOTE: Source code above as often - untested :)