Kohana 3 auth module, getting users with 'staff' or 'manager' role - php

I'm learning the framework, and now building an application using it.
I need to get all users that have 'user' or 'staff' role, but I couldn't find about it on the documentation.
Help anyone? (I think it's more an ORM problem the the auth module)

I didn't find an easy way to do this using the ORM, but I have a workaround.
This is my code for anyone who might encounter the same problem with me.
// One for each role
$staffs = ORM::factory('role', array('name' => 'staff'))->users->find_all()->as_array();
$managers = ORM::factory('role', array('name' => 'manager'))->users->find_all()->as_array();
// Merge the results
$results = array_merge($staffs, $managers);

May be you should create a separate ORM method for it? Something like this code:
public function get_users(array $roles)
{
$users = DB::select(array($this->_has_many['roles']['foreign_key'], 'id'))
->distinct(TRUE)
->from($this->_has_many['roles']['through'])
->where($this->_has_many['roles']['far_key'], 'IN', DB::expr('('.implode(',', $roles).')'))
->execute($this->_db);
if (count($users) == 0)
{
// return empty list
return array();
}
// now we need only IDs from result
$ids = array();
foreach($users as $columns)
{
$ids[] = $columns['id'];
}
// load users by id
return $this->where($this->_primary_key, 'IN', DB::expr('('.implode(',', $ids).')'))->find_all();
}
$roles is a role_id array (not names!).
PS. I dont remember how to query 'WHERE IN', so I use DB expressions.

Related

Laravel : How to get all the rows from a table except the first one?

I want to select all the users in my table "User" except the first One cause its the admin,
im using this function index in my controller but it doesn't work .
public function index()
{
// this '!=' for handling the 1 row
$user = User::where('id', '!=', auth()->id())->get();
return view('admin.payroll',compact('user'))->with(['employees' => User::all()]);
}
Better to used here whereNotIn Method
Note: first you find the admin role users and create a static array
$exceptThisUserIds = [1];
$user = User::whereNotIn('id', $exceptThisUserIds)->get();
It's not a good idea to specify the admin user with just id. A better design would be using some sort of a flag like is_admin as a property of your User model.
Still you can use the following code to get the users who have an id greater than 1:
User::where('id', '>', 1)->get()
For getting data skipping the first one you should use skip() method and follow the code like below
public function index()
{
$user = User::orderBy('id','asc')->skip(1)->get();
return view('admin.payroll',compact('user'))->with(['employees' => User::all()]);
}

Extract all possible values of AR column in yii2

Several models in yii2 are bound to a database using ActiveRecords. I now want to have a list of all ids of this model. Say, all user IDs when the Model is called User.
Sure I could just fetch all models and iterate over them, much like
$ids = [];
$users = User::find()->all();
foreach ($users as $user) {
$ids[] = $user->id;
}
But I feel there should be an easier way... Thanks in advance.
If you want to stay in ActiveRecord then this accomplishes the same thing:
$ids = User::find()->select('id')->column();
This returns array:
$ids = (new \yii\db\Query)->select('id')->from(User::tableName())->all();

Laravel query and array

please help me. I want to ask:
Let say I have 2 tables: user_master and people.
Now I am currently build an application in PHP with Laravel 5.1 framework that select the data from user_master table (with some constraint in where clause) and insert into people table.
The code is :
public function handle() {
$results = DB::select(DB::raw("SELECT * FROM user_master WHERE div_id = 1"));
foreach ($results as $res) {
//saving to array
//insert query to table people here.
}
}
My questions are:
How to save the result of select query to array, and
Insert that array into people table using RAW query (INSERT INTO people VALUES (...)).
P.S.: My query is RAW query, not using Eloquent. And please provide answer without Eloquent.
Thank you so much for any answer.
I have done the same scenario like this
$users=DB::table('Users')->where('created_at' ,'>=','2016-09-06')->get();
foreach ($users as $user){
DB::table('users_report')->insert(
array(
'id' => $user->id,
'username' => $user->username,
'lastname' => $user->lastname,
'email' => $user->email,
'created_at' => $user->created_at,
'updated_at' => $user->updated_at,
)
);
}
change your like according to your logic , its works 100% perfectly..
I think that is right
$results = DB::table('user_master')->where('div_id', 1)->get();
if your table and master have the same strucure, you just set the primary key in the below code. If they are not in the same structure, you have to ajust the results to the structure of the people bfore you insert to peopel table.
hope it will helps.
function delete_col(&$array, $offset) {
return array_walk($array, function (&$v) use ($offset) {
unset($v[$offset]);
});
}
public function handle() {
$results = DB::table('user_master')->where('div_id', 1)->get();
delete_col($results, $premiarykeyOfuser_master);
DB::table('people')->insert($results);
}

Laravel shows database row for test but not for other strings

I have actually no idea how I can fix this problem. I have tried quite a lot, so here is what I got:
I want to do a search function which checks different tables and different informations. Somehow I do only get results which I am directly related to (user_id in team table, the team I am in or my own username). My code looks like this:
public function search($param)
{
$result = ['users' => [], 'teams' => []];
$usersBySteamid = User::where('steamid', $param)->get();
$usersByName = User::where('username', 'LIKE', '%'.$param.'%')->get();
$teamsByName = Team::where('name', 'LIKE', '%'.$param.'%')->get();
$users = $usersBySteamid->merge($usersByName);
$result['users'] = $users;
$result['teams'] = $teamsByName;
return response()->json($result);
}
As a result I DO get my own username AND my own team, but not any other team or user.
Route:
Route::get('/admin/search/{param}', 'AdminController#search')->name('admin.search');
As a side information: I am using the auth middleware, but it did not make any problem until now, so I guess it might be irrelevant.

How to count_all() in Kohana 3.3 with Mysqli drivers

I am trying to use the count_all() method in kohana 3.3 to count all the rows of a table where the id equals a user_id. Here is my controller
public function action_get_messages()
{
$user_id = $this->request->param('id');
$messages = new Model_Message;
if ($user_id)
{
$messages = $messages->where('user_id', '=', $user_id);
$messages->reset(FALSE);
$message_count = $messages->count_all();
}
else
{
$message_count = $messages->count_all();
}
$pagination = Pagination::factory(array(
'total_items' => $message_count,
'items_per_page' => 3,
));
$pager_links = $pagination->render();
$messages = $messages->get_all($pagination->items_per_page, $pagination->offset, $user_id);
$this->template->content = View::factory('profile/messages')
->set('messages', $messages)
->set('pager_links', $pager_links);
}
But when i run the code i get these error message:
"Database_Exception [ 1054 ]: Unknown column 'COUNT("*")' in 'field list' [ SELECT COUNT("*") AS records_found FROM messages
AS message WHERE user_id = '2' ]"
What does this error mean and where is the error in my code?
Thanks in advance!
The error is on line 1054, which I would guess is the count_all() call.
I'm confused as to why you are calling a reset() on your object. This may be causing issues. You are also casting the object to itself, which is unnecessary. That section of code could look like this:
if ($user_id)
{
$messages->where('user_id', '=', $user_id);
$message_count = $messages->count_all();
}
I would advise using the ORM::factory to build your new models in the first place.
The Kohana documentation isn't great, but I would advise reading and looking through the ORM User Guide as ORM will save you a hell of a lot of time in the long run, especially if it's a large project.

Categories