yidas / codeigniter-model Goto Github PK
View Code? Open in Web Editor NEWCodeIgniter 3 Active Record (ORM) Standard Model with Laravel Eloquent & Yii2 AR like
Home Page: https://codeigniter.com/
License: MIT License
CodeIgniter 3 Active Record (ORM) Standard Model with Laravel Eloquent & Yii2 AR like
Home Page: https://codeigniter.com/
License: MIT License
setAlias()
doesn't seems to set alias for the table. Database throws error unknown table p.
Example:
$this->paf->setAlias('p')->find()
->join('co_user AS co', 'co.user_id = p.user_id')
->select('p.*')->get()->result();
I have problem using relationship with model inside a folder.
public function test()
{
return $this->hasOne('restapi/Test_model', 'id_test', 'id_test');
}
I already fix this problem by adding
// Original CodeIgniter 3 model loader
get_instance()->load->model($modelName);
// start by this line
$path = explode('/', $modelName);
if (count($path) > 1) {
$modelName = end($path);
}
// end line
$model = get_instance()->$modelName;
at line 1198. not sure if more bug will come.
Thank you
I have set 'is_unique' rule in one of my models. It works great when adding new rows in db. But if I try to load and then save an existing row, I get the 'The name field must contain a unique value.'.
I think on update it should not throw this error unless a different row has violated this rule.
Is there any workaround for this?
On line numbers 555 and 584 vscode hints that "$this can not be used in a static method" will this cause a PHP Error. If so then how do I fix this.
<?php
//Line 555
$instance = (isset($this)) ? $this : new static;
$record = $instance->_findByCondition($condition)
//Line 584
$instance = (isset($this)) ? $this : new static;
$query = $instance->_findByCondition($condition);
Will be glad if it's compatible with CI4
Model's email
property returning CI_Email instance .
e.g
$this->load->model('yidas/user_model', 'userModel'); print_R($this->userModel->email); exit;
p.s email is a field that exist in table columns
Few errors occured when I tried to update/save a model which was fetched by relation (hasOne). These are the following errors and the code snippet
You must use the "set" method to update an entry. Filename: D:/xyz/system/database/DB_query_builder.php Line Number: 1867
$rdf = $paf->rdf;
$rdf->save();
You must set the database table to be used with your query. Filename: D:/abhishek-phpprojects/RAE-AdminLTE/system/database/DB_query_builder.php Line Number: 1876
$rdf = $paf->rdf;
$rdf->id = 1;
$rdf->first_name = 'Hello';
prd($rdf->save());
last_name field is required , The "last name" field does contain the value fetched from database but validation still fails on required validator.
$rdf = $paf->rdf;
$rdf->first_name = 'Hello';
$rdf->save();prd($rdf->getErrors());
at line 357 in Model.php
return ($returnData) ? $data : true;
Why is empty $data is returned true?
This causes Model to save without running validations e.g
$this->load->model('yidas/Client_model', 'client');
$this->client->save();
I think will be usefull
Hi Nick,
Currently the findAll()
only takes in the query condition as a param but we cannot set Limit and offset for the active records. Would be great if you can add support for the record limit+offset so that not everyone have to override findAll()
to get this basic functionality.
btw Great work.
If I instantiate a new Model, and try to access the column values(which should should be empty), it throws Property id
does not exist error.
Code example:
$fileModel = new File_model();
if($fileModel->id){
echo 'Fixed';
}
I am using Jquery validation plugins for client-side validation in CodeIgniter and Server side using form_validation class.
Same as yii2 and laravel cant we use validation define in model for both client side and server side?
Hi Nick,
The validate method in Model.php has an issue in
$this->load->library('form_validation');
$this->form_validation->set_data($data);
$this->form_validation->set_rules($rules);
// Run Validate
$result = $this->form_validation->run();
If there is other form validation instance present which is accessible $this->form_validation then validate method applies rules from other instances as well(because it's the same instance infact).
I think you should change the instance name from form_validation to something random and unique to a model.
p.s Great work.
Hi Yidas ,
It'd be great if we can access the changed/old attributes values of a model.
Would be great if you can add two new public methods beforeSave & afterSave that can be overridden to perform any task before saving a model just like in Yii2 active record.
You can call the methods inside save()
and afterSave should be called only if the saving operation was successful.
hello sir, how can all the data not be displayed for soft delete with a query like below
return $this->find(true)
->or_like('id', $q)
->or_like('username', $q)
->or_like('password', $q)
->or_like('email', $q)
->or_like('fullname', $q)
->or_like('phone', $q)
->limit($limit, $start)
->order_by($column, $sort)
->get()
->result();
}
in fact the above query shows all data including soft delete, thaks you
Helloo & Thank you for this library,
I wanna ask something about ORM features
$this->load->model('Posts_model');
$post = $this->Posts_model->findOne(1);
if ($post) {
$post->title = 'New CI3';
$result = $post->save();
}
At above scripts, is it really need to find record first for updating the records? I hope it can be just like this:
$this->load->model('Posts_model');
$post = new Posts_model;
$post->id = 1;
$post->title = 'New CI3';
$result = $post->save();
Terima Kasih, ๐
Hi @yidas
At line 1097 why the _writeProperties
are emptied/resetted?
Is there any particular reason behind that ?
Hi nick
When we save a model the fields like updated_at
created_at
aren't populated unless we re-fetch the model,
So adding a refresh method like in Yii2 ActiveRecord will be helpful to re-fetch the latest data of the row.
How does the cache work with this library? Thank you
I am getting two different arrays for relational model.
Like Model - 1:
[_readProperties:yidas\Model:private] => Array
(
[id] => 1
[value] => 545488
[data] => 1
)
with this $vendors = $model->vendors; I am getting another data.
Here model 1 hasOne relation with vendor table.
My requirement and yii2 also gives relational query data in single array
(
[id] => 1
[value] => 545488
[data] => 1
[verndor] => ()
)
and how to get array of query $model = $this->Vendor_model->findAll();
On both of CREATED_AT
and UPDATED_AT
, it said:
/**
* @string Feild name for created_at, empty is disabled.
*/
But in reality they don't work that way. You may test it yourself by set them empty or either one. Eg. there will be an error on model insertion and stuff.
Hi,
I'm new to Eloquent and would like to use it in CodeIgniter. Your project looks great! In your documentation, I don't see examples of accessing related models, for example:
An Author has many Blog_posts.
A Blog_post can have many Comments.
I would like to access related models, such as:
$author = $this->Author_model->findOne(1); // retrieve the Author with id = 1
$blog_posts = $author->blog_posts->comments->findAll(); // retrieve all Comments for all Blog_posts by this Author
Is this possible with your project?
Thank you
$this->Groupvendors_model->findOne(1);
and give me error query :
SELECT * FROM "group_vendor" WHERE "group_vendor
"."id
" = 1 ORDER BY 1 OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY
Hi, while using codeigniter-model with yidas/codeigniter-psr4-autoload a problem occurs.
When I create a hasMany relation in a model
public function users(){
return $this->hasMany('\app\models\User', 'group', 'id');
}
the codeigniter loader cannot find the class, if i change \app\models\User to User the loader cannot load the class because of the namespace.
For now I have found a solution to declare the model inside the function and it seems to solve the problem:
public function users(){
$u = new User();
return $this->hasMany('\app\models\User', 'group', 'id');
}
It took me a while so I'm posting to let you know about the problem, any maybe for anyone to find the solution.
ORM should throw error when a property's value is assigned which doesn't exist. e.g
$model->additional_info = 1; $model->save();
additional_info
is not a property of the $model
, and it should throw error when value is assigned to it.
Database throws error about the wrong column name.
I think __set()
should be somewhat similar to __get()
.
I found this error on update from ORM using save function :
this is my code :
$model->id_services_category = $this->input->post('id_services_category', TRUE);
$model->id_organization = $this->input->post('id_organization', TRUE);
$model->service_name = $this->input->post('service_name', TRUE);
$model->service_description = $this->input->post('service_description', TRUE);
if ($model->save()) {
redirect('/services');
}
and then I edit file src/Model.php on line 1565
with :
protected function _field($columnName)
{
if ($this->getDatabase()->dbdriver == 'sqlsrv') {
return ($this->alias) ? "{$this->alias}.{$columnName}" : "{$this->table}.{$columnName}";
}
return ($this->alias) ? "`{$this->alias}`.`{$columnName}`" : "`{$this->table}`.`{$columnName}`";
}
is there another way to overcome this ?
Hello,
seems there is a bug with codeigniter "dbprefix" while using findOne and other WHERE methods.
for example:
$this->Products_model->findOne($id)
cause the following error:
Unknown column 'pl_`products.id' in 'where clause'
SELECT * FROM pl_products
WHERE pl_``products
.id
= '1' LIMIT 1
I made a quick fix this change:
protected function _field($columnName)
{
if ($this->alias)
{
return "`{$this->alias}`.`{$columnName}`";
}
if (!$this->_db->dbprefix)
{
return "`{$this->table}`.`{$columnName}`";
}
return "{$this->table}`.`{$columnName}`";
}
how can i count number of records in table where status = 1?
@yidas, its nice to have implementations to support hasManyThrough
and hasOneThrough
like in Laravel.
References:
hasOne does not work with empty(). The function always returns true.
Example:
echo $object->hasOneObject->key; // 25
var_dump(empty($object->hasOneObject->key)); // true
Hello bro,
Thank you for your library
I am using Postgresql
here is error:
Error Number:
ERROR: missing FROM-clause entry for table "games
" LINE 3: WHERE "games
"."id
" = 2 ^
SELECT * FROM "games" WHERE "`games`"."`id`" = 2 LIMIT 1
I use findOne(id) function
Can you take a look on this problem?
Thanks,
Hi,
I needed the order_by method when using findAll. I added for myself as follows. Can an order_by be added for available use?
// Find the active recordd whose type is 'A' and whose status is 1 and order by column name
$activeRecords = $this->Model->findAll(['type' => 'A', 'status' => 1], 'id');
// Find the active recordd whose type is 'A' and whose status is 1 and order by with array column name => [asscending - asc | descending - desc]
$activeRecords = $this->Model->findAll(['type' => 'A', 'status' => 1], ['id' => 'ASC']);
$activeRecords = $this->Model->findAll(['type' => 'A', 'status' => 1], ['id' => 'ASC', 'created_at' => 'ASC']);
public static function findAll($condition=[], $orderBy=null, $limit=null)
{
$instance = (isset($this)) ? $this : new static;
$query = $instance->_findByCondition($condition);
// orderBy
if ($orderBy) {
$type = 'DESC';
$column = $orderBy;
if (is_array($orderBy)) {
foreach ($orderBy as $orderColumn => $orderType) {
$query = $query->order_by($orderColumn, $orderType ?? 'DESC');
}
} else {
$query = ($column && $type) ? $query->order_by($column, $type) : $query;
}
}
.........
}
Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.