简体   繁体   中英

Where condition based on two database fields

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM