Giter VIP home page Giter VIP logo

codeigniter-model's Issues

setAlias() not working

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

Relationship with model inside folder

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

'is_unique' validation rule won't let me update data

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?

VSCode hints on $this in Static Method

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

Model Saving Issue when fetched via Relation

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

  1. 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();

  2. 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());

  3. 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());

Empty model saved without running validation

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

Limit & Offset in Find All method

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.

Property does not exists

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';
}

form validation pass through model

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?

Form Validation instance clashing with other Form validation instances

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.

Before Save and After Save event/Method

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.

data is deleted always appear for query or_like on soft delete

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

ORM feature Save & Update

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, ๐Ÿ‘

Add refresh method to re-populate data

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.

Cache

How does the cache work with this library? Thank you

Two different arrays for relational models

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

CREATED_AT and UPDATED_AT aren't optimal at all.

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.

Example of accessing a related object (model)

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

does it work for MS SQL?

$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

hasMany/hasOne not working with yidas/codeigniter-psr4-autoload

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.

Unknown column error

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.
er

I think __set() should be somewhat similar to __get() .

Throw Property does not exist error if value is null

ORM throws Property does not exist error if property's value is null in database.
I think you should add key exists check in function __get($name) of Model.php (line 1351 & 1355) instead of isset.
error
BTW you did a really good job with this Project.

Error save data on update from ORM (Sql Server)

I found this error on update from ORM using save function :

Screen Shot 2019-11-14 at 14 27 27

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 ?

findOne with dbprefix

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}`";
}

hasOne does not work with empty()

hasOne does not work with empty(). The function always returns true.
Example:
echo $object->hasOneObject->key; // 25
var_dump(empty($object->hasOneObject->key)); // true

findOne error with postgresql

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,

Can order_by be added to findAll method?

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

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.