Codeigniter - Multiple database prefixes - codeigniter

I'm in process to migrate an old webapp to codeigniter, everything looks good other then that the database has 3 kind of tables with different table prefixes.
the app's native tables use mci_ as prefix
tables which hold inter departmental data (kind off) use mdept_
and tables handling non-native data use mext_ as prefix
now as I understand we can set one prefix for entire database
'hostname' => DB_HOST,
'username' => DB_USER,
'password' => DB_PASS,
'database' => DB_NAME,
'dbdriver' => 'mysqli',
'dbprefix' => 'mci_',
and query builder will use mci_ for all tables.
My question is, is there a way to use rest of the 2 prefixes (mdept_, mext_) with query builder rather then having the direct approach db->query
Thanks

Solution #1:
You can set $this->db->dbprefix = "mdept_" before $this->db->select()...get();. But this will work if there is only one table in the query. And if there are other queries below, then you also need to redefine dbprefix again.
Solution #2:
Add for mdept_... and mext_... tables the prefix mci_. I.e mci_mdept_users. No need to change the database config, redefine the prefix, just specify the table names in the queries along with the old "prefixes".
Solution #3:
Delete prefix in config at all: 'dbprefix' => '', and use full table names with prefixes in queries.
Solution #4. The best solution of these, in my opinion
Add a view with the mci_ prefix to your database: CREATE VIEW mci_old_mdept_users AS SELECT * FROM mdept_users;. All that the view will do is to get data from a table that you cannot rename. And in your application you can write simply: $this->db->get('old_mdept_users');.
Solution #5. If all queries use tables with the same prefixes
Divide tables into 3 databases. Add these databases in the config:
$db['default'] = array(
...
'dbprefix' => 'mci_',
...
);
$db['mdept'] = array(
...
'dbprefix' => 'mdept_',
...
);
$db['mext'] = array(
...
'dbprefix' => 'mext_',
...
);
Add other connections in MY_Model:
protected function connect_mdept_db()
{
$this->mdept_db = $this->load->database('mdept', TRUE);
}
Use these connections:
$this->connect_mdept_db();
$this->mdept_db->get("users"); // uses "mdept_users" table

Related

How to add validation for preventing duplicate level points in laravel query?

Here is a table named stages and below are the fields
I don't want to allow to add the same from and to points example, if points from 1 to 10 is already added means not allow them to add the same range, another one condition is don't allow to add in between points example in-between 1to 10 like 5 to 7 are also not allowed.
Tried laravel query
$isexist = Stage::whereBetween('from', [$request->from, $request->to])
->orWhereBetweenColumn('to','from', [$request->from, $request->to])->exists();
but it not satisfying all conditions.
Any one please help, thanks in advance.
you can validate the data like this
$validator = Validator::make($inputData, [
'label' => 'required|unique:tableName,label'
]);
if($validator->fails()){
//Throw validation errors
}
Or you can use
Model::query()->updateOrCreate(['label' => $request->label], [
'from' => $request->from,
'to' => $request->to
]);
Read more on unique validation reference: https://laravel.com/docs/9.x/validation#quick-writing-the-validation-logic

Problem with adding record to database after seeds in Laravel

I add test records to the database using seeds
public function run()
{
DB::table('categories')->insert([
['id' => 1,'name' => 'Select a category', 'slug' => null],
['id' => 2,'name' => 'Computers', 'slug' => 'computer-&-office'],
]);
}
But then, if I want to add a new record to the database, already through the form, I get the error
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "categories_pkey"
I understand that when I add a new record through the form, it is created with id = 1, and I already have this id in the database. How can I avoid this error?
You should remove id from insert() and make it auto increment in mysql,
It complains about a unique constraint, meaning your primary key is indexed as "categories_pkey" or you have another field that is unique.
This happens because you are inserting a record and a record already exists where that column must be unique.
In general production workflow, when you add a record you never specify an ID. Most cases (there are exceptions) ID is an autoincrement integer, meaning it adds up automatically. On the first insert the database set its ID to 1, the second to 2 and so on.
As a seeder, its generally a good idea to set up the ID so you know that a certain ID matches a certain item (as a base content of a project like user states or roles).
As a regular workflow (from a form submission), you can have something like this
DB::table('categories')->insert([
['name' => 'some value', 'slug' => 'some slug']
]);
However, I don't advise to use DB::table when Laravel provides ActiveRecords pattern (ORM, called Eloquent) which you should take a look here.
https://laravel.com/docs/8.x/eloquent#introduction
Besides the benefits of layer abstraction and working with activerecords, It produces a much cleaner code like
$data = ['slug' => 'some slug', 'name' => 'some name'];
Category::create($data);

unique between 2 columns

i need to create a validation to my table "candidate_knowledges", basically in this table it accepts to columns (candidate_id, software_id), i cannot let create user_id and software more then one. but i think my validation is wrong or im not doing it right.
What im trying to say in validation is that can only exist one software_id and one candidate_id on the table, this way the candidate dont have duplicate entries.
Ex: 'software_id' => 'required|integer|unique:candidate_knowledges,candidate_id,'.$candidate->id,
Here is a way to allow only one software for each candidate:
$rules = [
'software_id' =>
'required',
'integer',
'min:1',
Rule::unique('candidate_knowledges')->where('candidate_id', $candidate->id),
],
];
In general I would suggest using fluent validation syntax (it's match easier to use and update), but if you can't (laravel < 5.3 or any other reasons):
'software_id' => 'required|integer|unique:candidate_knowledges,NULL,NULL,candidate_id,' . $candidate->id,
Hope it helps.

Laravel Create Record and Use ID Value in Another Column

When I create a new record in my Fan model, at the same time that I create the new Fan record, I want to use the new ID value in another column. I'm trying to do this all at once and not have another method to go back and update the record.
$fan = Fan::create([
'display_name' => $displayName,
'bio' => $bio,
'logo_url' => $logoUrl,
'algolia_id' => 'fan_'??, // I want to replace ?? with this record's ID value.
]);
I've tried $fan, but doesn't work since that variable isn't created yet. I cannot use Auth because the ID isn't the Auth user's ID.
Thanks!
I doubt you can automatically do it, you should do it in 2 steps:
$fan = Fan::create([
'display_name' => $displayName,
'bio' => $bio,
'logo_url' => $logoUrl
]);
$fan->algolia_id = 'fan_' + $fan->id;
$fan->save();
That said, it's not a great database design, you'd rather want to build the algolia_id field when you need to use it, since you'd store duplicated value (the id and the algolia_id are the same except for fan_).

Multiple Queries in Codeigniter [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
MYSQL multiple insert in codeigniter
I would like to execute multiple insert queries simultaneously using codeignitor framework in PHP.There is any simple ways to do this without writing multiple insert queries.Already tried something like
$this->db->query('INSERT INTO students (first_name, last_name) VALUES
('teejay', 'obazee')'
('maev', 'shadowsong')'
('jaina', 'proudmore')', FALSE)
.There is any ways like this.Which is not working.If anybody knows;please help me.
You can use codeignitor native active record
$data = array(
array(
'first_name' => 'teejay', 'last_name' => 'obazee'
),
array(
'first_name' => 'maev', 'last_name' => 'shadowsong'
),
array(
'first_name' => 'jaina', 'last_name' => 'proudmore'
)
);
$this->db->insert_batch('students', $data);
It will produce query
INSERT INTO students (first_name,last_name) VALUES ('teejay', 'obazee'),('maev', 'shadowsong'),('jaina', 'proudmore');
I also had problem with sending multi queries in CodeIgniter.
In your specific situation, you could send multi rows in one INSERT query, but in many other situations this is not possible because you have different commands (eg LOCK TABLE... SELECT... INSERT... UPDATE... UNLOCK TABLES)
At that point in codeigniter you should user:
mysqli_multi_query($this->db->conn_id, $sql);
I didn't even know the answer, the answer was originally posted as a comment by Kumar (https://stackoverflow.com/users/523794/kumar) at Codeigniter - how to run multiple/batch queries?
Note: You have to set you database driver to mysqli in /application/config/database.php
Hope it helps some one.
Unfortunately, you need to do something like:
$this->db->query("INSERT INTO `students` (`first_name`,`last_name`) VALUES ('teejay', 'obazee'),('maev', 'shadowsong'),('jaina', 'proudmore')");
Or use someone else's class to build the query:
http://codefury.net/2009/12/insert-multiple-rows-into-a-database-with-codeigniter/

Resources