I have two controllers LeaveApplicationsController and EmployeesController. In LeaveApplicationsController index action I'm displaying leave records of all employees. It is showing fine but what I need is to show only login employees leaves to that employee. I have employee_id as foreign key in leave_applications table. But I am not getting employee_id (which is id) from employees table. I also have users table and each user has one employee associated with it. So when employee is created, before that user is created and newly created user's id is also stored in employees table under unser_id field. So user_id is foreign key in employees table and uniquely identifies the employee.
This is my LeaveApplicationsController.php code:-
public function index()
{
$userId = $this->Auth->user('id'); //gets current user's id
$this->LeaveApplication->recursive = 0;
$leavereqs = $this->set('leaveApplications', $this->Paginator->paginate());
$employeeId = $this->Employee->find('all', array('fields'=>array('id'), 'conditions'=>array('Employee.user_id'=>$userId))); // code for getting emp id
return $this->LeaveApplication->find('all', array('conditions'=>array('LeaveApplication.employee_id'=>$employeeId))); //code for fetching current employee record
}
But this shows error. Please tell me where am I doing it incorrect? I'm also using $uses to load Employee model in LeaveApplicationsController. Thanks.
public function index()
{
$userId = $this->Auth->user('id'); //gets current user's id
$this->LeaveApplication->recursive = 0;
$leavereqs = $this->set('leaveApplications', $this->Paginator->paginate());
$employeeId = $this->Employee->find('list', array('fields'=>array('id'), 'conditions'=>array('Employee.user_id'=>$userId))); // code for getting emp id
return $this->LeaveApplication->find('all', array('conditions'=>array('LeaveApplication.employee_id'=>$employeeId))); //code for fetching current employee record
}
find('all') will return array with index Employee and id
Imp links: find('all'), find('first') and find('list')
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-first
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-all
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#find-list
Related
I do have two tables which are employee and loan
When I enter loan for particular user I am picking user employee_id and loan amount.
// loan form
https://imgur.com/VH6hflw
these details stores in loan table. As well as I have stored some employees details already in employee table like account number, employee official id, userpic.
When I submitting the loan form I am getting employee unique id. I will store the employee unique id to loan field called loan_employee_id.
My problem is When I retrieve the data from the loan table I will get loan amount but some more field are needs from employee table. So I have joined with two tables which are employee and loan.
my db structure https://imgur.com/XYxGjVH
public function fetchLoan()
{
$this->db->select('*');
$this->db->from('employee');
$this->db->join('loan','employee.emp_id = loan.employee_loan_id');
$this->db->where(array('loan.employee_loan_id' => "employee.emp_id") );
$query= $this->db->get();
return $query->result_array();
}
Here where condition should match with employee_loan_id from the loan table and emp_id from employee table
How Do i join the tables with above condition, where conditions both valion getting from the database.
First of all, the corresponding MySQL query would be:
SELECT * -- Put field names which are required
FROM loan
INNER JOIN employee ON employee.emp_id = loan.employee_loan_id
WHERE loan.employee_loan_id = 12; -- Consider we're fetching records for emp_id = 12
Corresponding code would be:
-- Pass a parameter for employee id for which you want to get loan details.
public function fetchLoan($empId)
{
$this->db->select('*');
$this->db->from('employee');
$this->db->join('loan', 'employee.emp_id = loan.employee_loan_id');
$this->db->where('employee.emp_id', $empId);
$query = $this->db->get();
return $query->result_array();
}
Please pass employe_unique_id on this based data geting
public function fetchLoan($employe_unique_id)
{
$this->db->select('*');
$this->db->from('employee');
$this->db->join('loan','employee.id = loan.employee_id');
$this->db->where('employee.id',$employe_unique_id);
$query= $this->db->get();
return $query->result_array();
}
TLDR: How do I create a relationship from one table to another? For example, I want changes from the user table automatically reflect on to the supplier table? Something like it's just referencing from the user table.
I have this 2 tables
========================
USER table
1. id
2. username
3. password
4. name
========================
and
========================
SUPPLIER table
1. id
2. username
3. name
========================
Every time I add a new user, it should automatically be saved into the supplier table. This is what I did:
function saveUser($postdata) {
$newUser= new \App\UserModel;
$newUser->email = $postdata['email'];
$newUser->password = $postdata['password'];
$newUser->name = $postdata['name'];
$newUser->save();
$this->saveSupplier($postdata['email'], $postdata['name']);
}
function saveSupplier($email, $name) {
$newSupplier = new \App\SupplierModel;
$newSupplier->email = $email;
$newSupplier->name = $name;
$newSupplier->save();
}
You see, it's not in a relationship right. It's just like manually saving into two tables. How do I make the Supplier table dependent on the user table? For example, everytime I make changes in the User table, it will automatically reflect on to suppliers table without having to fire an update method.
One way to achieve this would be to register and event in the boot method of your
User model.
protected static function boot()
{
parent::boot();
static::created(function($user) {
Supplier::create([
'username' => $user->username //or email or whatever you have.
'name' => $user->name
]);
});
}
Do you might be interested in triggers. If you can create triggers you can use them to insert into SUPPLIER every time you insert in USER.
Something like:
CREATE TRIGGER t_reflect_changes_user_supplier
AFTER INSERT
ON USER FOR EACH ROW
BEGIN
-- trigger code
INSERT INTO SUPPLIER (username,name) VALUES new.username,new.name
END;
I have a pivot table. The name is users_banks table. The table have field id, user_id, bank_id, status, account_name and account_number
Now, the pivot have 3 records
I display contain from pivot table using code like this :
$user_id = auth()->user()->id;
$user = $this->user_repository->find($user_id);
$account = array();
foreach($user->banks as $bank) {
$account[] = $bank;
}
dd($account);
The result display all record in the form of array. There exist value of field user_id, bank_id, status etc. But I don't find value of id
How can I find id from pivot table?
If the relationship is defined correctly you can use:
$bank->pivot->id
but make sure the user belongsToMany(Bank::class) and the bank belongsToMany(User::class) or else it wont work.
I have a Block model which is basically for blocked users. It has a target_id and a sender_id, both of which are IDs from the users table. How can I add data to this pivot table when a user wants to block another user? What should my relationship methods look like?
Since both target_id and sender_id are fields from the users table, your relationship must be defined this way.
class User {
public function blocks() {
return $this->belongsToMany('App\User','blocked_users','sender_id','target_id')->withPivot(['id']);
}
public function blockedBy() {
return $this->belongsToMany('App\User','blocked_users','target_id','sender_id')->withPivot(['id']);
}
}
Here blocked_users is the name of the table.
So, to block a user you can do :-
//User who is going to block
$user = User::find($id);
$inputs = [$target_user_id];
$user->blocks()->attach($inputs);
//or you can use,
$user->blocks()->sync($inputs, false);
The false in the above sync is used when the old synced rows are ignored and new ones are attached.
To get the list of users who that particular user has blocked, you can do :-
$user = User::find($id);
$user->blocks;
And to get the list of users who that particular user is blocked by
$user = User::find($id);
$user->blockedBy;
Thanks,
I have a leave_applications table and an employees table. When an employee applies for a leave that is stored in leave_applications table along with employee id.
When next time employee logs in I am displaying leave applications he has applied for so far. But the problem is all leave applications are being displayed (even from other employees) which should not be the case. So how to I restrict that only the logged in employee sees his leave applications?
My LeaveApplicationsController.php page is this which displays leaves:
public function index()
{
$this->LeaveApplication->recursive = 0;
$leavereqs = $this->set('leaveApplications', $this->Paginator->paginate());
//return $this->LeaveApplication->Employee->find('all', array('conditions' => array('LeaveApplications.employee_id'=>$this->Auth->user('id'))));
return $this->LeaveApplication->find('all');
//echo $log_user_id = $this->Auth->user('role'); die();
//return $this->LeaveApplication->Employee->query("SELECT * FROM leave_applications WHERE employee_id = '$log_user_id'");
//return $this->LeaveApplication->Employee->query("SELECT la.leave_type, la.subject, la.detail, la.from_date, la.to_date, la.applied_on, la.leave_status, la.leave_status_date FROM leave_applications la INNER JOIN employees e ON la.employee_id = e.id INNER JOIN users u ON e.user_id = u.id WHERE la.employee_id = '$log_user_id'");
}
Please note that I have this code in LeaveApplicationsController.php not in EmployeesController.php because when employee clicks on all leaves button/link this controller's index view is called.
Commented code is what I tried but none of them are working.
Make sure the employee ID from Auth is ok.
Query the leave table, where the employee_is is the logged in user
$employeeId = $this->Auth->user('id');
return $this->LeaveApplication->findAllByEmployeeId($employeeId);
index function must something like:
public function index()
{
$id = "GET EMPLOYEE ID FROM SESSION OR BY PASSING ARGUMENT";
$this->LeaveApplication->recursive = 0;
$conditions = array("employee.id" => "$id");
$leavereqs = $this->set('leaveApplications',
$this->Paginator->paginate('MODEL NAME', $conditions)
);
}
To get leave applications of the logged in Employee, you should specify the Employee_id in your find function:
public function index(){
//Make sure the Employee is logged in
$id = $this->Auth->user('id');
if($id){
// get leave applications of logged in Employee
$leavereqs = $this->LeaveApplication->find('all', array(
'conditions'=> array('Employee_id'=>$id)
));
$this->set('leavereqs',$leavreqs');
}
}
If it doesn't work for you, Debug the $this->Auth->user() and make sure that in your database you assign Employee_id to leave applications.
You can use magic find types like this:
findAllByEmployeeId($emp_id)
only in case when your field name in database is employee_id.
Another way of getting data is :
find('all',array('conditions' => array('employee_id' => $emp_id));