3

I'm trying to learn CodeIgniter and just getting my hands dirty with the model component of the MVC architecture.

I first tried using the query builder but found that it keeps adding quotes to my table/column names. A way to fix that is to use all caps on them and that fixed it. I hate writing in all caps though so I decided to just not use the query builder and do $this->db->query(); instead.

The issue I have with this right now is that I have to constantly write the schema with the table name: SELECT * FROM schema.table_name. I would like to avoid having to write schema. for all tables I need to reference.

I browsed the documentation and saw a configuration for setting schemas however it seems like it's only used with PostgreSQL and ODBC drivers. I still tried it but of course it didn't work as I expected. I still get an error saying the table could not be found.

NOTES:

I am logged in as my user but I need to run queries as a different user - i.e. logged in as user1 but need to run queries as user2.table_name.

3
  • @ no backticks: stackoverflow.com/a/31111046/2275490 Commented Aug 30, 2018 at 22:59
  • @ schema: documentation of CI 3.0 says: The database schema, defaults to ‘public’. Used by PostgreSQL and ODBC drivers. Commented Aug 30, 2018 at 23:06
  • @Vickel I already solved the problem with quotes by doing $db['default']['_protect_identifiers'] = false;. Do you know of a way to avoid needing to constantly supply the schema? Commented Aug 31, 2018 at 17:45

1 Answer 1

2

So I was able to solve this by adding a __construct() on my model class.

class My_model extends CI_Model {
  public function __construct() {
    $this->db->query("ALTER SESSION SET CURRENT_SCHEMA = my_schema");
  }

  public function get_awesome_user() {
    $this->db->select("u.username, u.firstname, u.lastname");
    $this->db->from("sys_users u");
    $this->db->where("u.username", $this->input->post("username"));

    $query = $this->db->get();
    return $query->result();
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.