ExpressionEngine CMS
Open, Free, Amazing

Thread

This is an archived forum and the content is probably no longer relevant, but is provided here for posterity.

The active forums are here.

Gas ORM

October 23, 2011 4:00pm

Subscribe [45]
  • #181 / Jan 19, 2012 12:01am

    toopay

    1583 posts

    Can I tell Gas that I only want the ‘id’ and ‘username’ fields from the users table and the ‘id’ and ‘email’ field from the emails table? I found out that I can add ->select() to tell Gas what to get from the users table, but what about the email table?

    This is what added on in the latest version. You could have something like :

    function _init()
    {
       // Define relationships
       self::$relationships = array(
          'wife' => ORM::has_one('\\Model\\Wife', array('select:id,name')),
          'job'  => ORM::has_many('\\Model\\Job\\User => \\Model\\Job', array('select:id,name')),
       );  
       // Define fields definition
       self::$fields = array(
          'username' => ORM::field('char[10]', array('required', 'callback_username_check')),
       );
    }

    In user table, so when you load your related entity, you could include some pre-process query you want (select, order_by and limit). Look around at the repo, in the develop branch within unit test section for furthermore usage.

    Also, can I eager load multiple levels? For example if there is another m:m relationship after emails?

    In latest version, sure. You could have something like :

    // Relationship statement block….
    'acl'  => ORM::has_many('\\Model\\Role\\User => \\Model\\Role <= \\Model\\Acl\\Role => \\Model\\Acl', array('select:id,name')),

    for example, which actually connectiong ‘user’ table in several tier level of tuple(s) to reach the ‘acl’ table.

  • #182 / Jan 19, 2012 5:28am

    sqwk

    83 posts

    // Relationship statement block….
    'acl'  => ORM::has_many('\\Model\\Role\\User => \\Model\\Role <= \\Model\\Acl\\Role => \\Model\\Acl', array('select:id,name')),

    for example, which actually connectiong ‘user’ table in several tier level of tuple(s) to reach the ‘acl’ table.

    Not entirely sure about the syntax here. Could you explain what all the \\, => and <= are doing?

  • #183 / Jan 19, 2012 6:13am

    toopay

    1583 posts

    ‘\\’ is used, because all gas model should have namespace, and in string variable we cannot write ‘\’.
    And ‘=>’ or ‘<=’ is to simplify our relationship paths. The relationship interpreter, will parsing and break down above path into paired tuples as follow :

    //'=>' mean LEFT is belongs to RIGHT
    //'<=' mean RIGHT is belongs to LEFT
    
    // Level 1 :
    // \Model\User <= \Model\Role\User
    
    // Level 2 :
    // \Model\Role\User => \Model\Role
    
    // Level 3 :
    // \Model\Role <= \Model\Acl\Role
    
    // Level 4 :
    // \Model\Acl\Role => \Model\Acl

    To generate the most efficient SQL query to reach ACL from USER, if there is a request from method like :

    $user = Model\User::find(1);
    
    // Then to retrieve corresponding acl, its done in one SQL query
    // Bellow will output corresponding acl for user with primary key = 1
    var_dump($user->acl());

    Otherwise, like in earlier version of this ORM, identical task with above will need with something like :

    $user1 = Gas::factory('user')->find(1);
    $roles = $user1->roles;
    $acl   = array();
    
    foreach ($roles as $role)
    {
       $acl[] = $role->acl;
    }
    
    // Here, we could finally get all user'a acl(s),
    // But it will execute so much SQL (which supposed to resolved by each entity definition)
    var_dump($acl);

    Which both inefficient in its executed SQL command(s) and code(s) usage.

  • #184 / Jan 19, 2012 8:35am

    sqwk

    83 posts

    Is it just me or is that a completely different syntax to what is listed in the wiki?

  • #185 / Jan 19, 2012 12:18pm

    toopay

    1583 posts

    Its for 2.0, and i did not update the wiki yet. Version 1.X.X syntax will remain, as is. There are several things left, to completely release this new version. I just answer your previous question, regarding possibility to achive those task, within this new version.

  • #186 / Jan 23, 2012 11:04am

    brunobarros

    2 posts

    @toopay I’m trying to implement Gas on my already born system. I do something similar to Wordpress. I have a table “content” with posts, categories etc.
    ===========
    content
    ===========
    id
    title
    category_id
    ===========

    If the line is a category the category_id is ‘0’, otherwise it is the ID of a category.
    In this case, do I need one single Model? I tried both, mapping with one and two models, one to posts and another to categories… but I could not get the category title.

    Ex: $content->title
    Ex: $content->category->title

    Is it possible?
    Tnks

  • #187 / Jan 23, 2012 1:11pm

    toopay

    1583 posts

    @brunobarros,
    You could use self-referential option if you go with one table.

  • #188 / Jan 23, 2012 2:05pm

    brunobarros

    2 posts

    Yeah man, I did it and works. See…

    Content_gas
    public $relations = array(
            'belongs_to' => array('content' => array(
                    'self' => TRUE,
                    'foreign_key' => 'category_id')
                )
    }

    And I called the GAS:

    $posts = Gas::factory('content')->where(array('category_id !=' => 0))->with('content')->all();

    Inside de loop:

    foreach ($posts as $post) {           
        echo $post->title . ' - category: ' . $post->content->title . '
    ';
    }

    Is there a way to do it better? If a could reference the category using: $post->category->title would be much better, don’t you think?

  • #189 / Jan 24, 2012 9:48pm

    toopay

    1583 posts

    @brunobarros,

    In version 2.0, there will be more flexible way to do that. In version 1.X, i’m affraid, it was the only solution. Not too pretty for sure, to have those, but at least it works as expected 😊

  • #190 / Jan 25, 2012 9:09am

    quasiperfect

    132 posts

    i tried to use gas but i get a error maybe someone can help
    the error is Fatal error: Class ‘User’ not found

    i use latest gas,codeigniter from git
    and @wiredesignz hmvc extension

    i even tried to load user model but no luck i get Fatal error: Call to undefined method Gas::load_model()

    in my gas config i have

    $config['models_path'] = array(APPPATH.'models', APPPATH.'modules');
    $config['models_suffix'] = '_gas';
    $config['autoload_models'] = TRUE;
    $config['cache_request'] = TRUE;
    $config['auto_create_models'] = FALSE;
    $config['auto_create_tables'] = TRUE;

    i have models/user_gas.php

    class User extends Gas
    {
     public $table = 'users';
     public $primary_key = 'id';
     public $relations = array(
      'has_many' => array('comment' => array()),
     );
    
     function _init()
     {
      $this->_fields = array(
       'id' => Gas::field('auto[11]'),
       'username' => Gas::field('char[6,15]'),
       'password' => Gas::field('char[6,15]'),
       'email'    => Gas::field('email'),
       'created_at' => Gas::field('datetime'),
       'updated_at' => Gas::field('datetime'),
       'deleted_at' => Gas::field('datetime'),
       'delted' => Gas::field('int[1]'),
      );
      $this->_unique_fields = array('email', 'username');
      $this->_ts_fields = array('updated_at');
     }
    }

    and i call gas like this

    $data = array(
       'username' => 'myusername',
       'email'    => '[email protected]',
       'password' => md5('[email protected]'),
       'created_at' => date("Y-m-d H:i:s"),
       'updated_at' => date("Y-m-d H:i:s"),
       'deleted_at' => '',
       'delted' => 0,
      );
      $new_user = new User;
      $new_user->fill($data, TRUE);
      if ( ! $new_user->save(TRUE))
      {
             echo $new_user->errors('', '');
             echo 'The raw errors were : ';
             print_r($new_user->errors);
      }
      else
      {
             echo 'New user successfully created. And her id is '.$new_user->last_id();
      }
  • #191 / Jan 25, 2012 9:35am

    toopay

    1583 posts

    I cant replicate those behaviour. What version you are using? In very earlier version, it just accept string at `models_path` configuration.

  • #192 / Jan 25, 2012 9:10pm

    khavayero

    14 posts

    Hello Toopay,

    I have a easy questions,

    When I use static method for save a record, the method errors is empty, why?

    Example:

    $sales = new Sales();
    if ($sales->fill($arrSale, TRUE)->save(TRUE)){
       echo "ok";
    }else{
       print_r($sales->errors); //out: [name_field] : .....error description
    }

    But…..with static method

    if (Gas::factory('sales')->fill($arrSale, TRUE)->save(TRUE)){
       echo "ok";
    }else{
       print_r(Gas::factory('sales')->errors); //out: is empty
    }

    Thanks a lot!!

     

  • #193 / Jan 26, 2012 3:53am

    quasiperfect

    132 posts

    @Toopay i solved my previous problem by redownloading gas

    now i have a diferent question

    let’s take as example a dating site where a user has a profile page and people can post comments on that page and comments to comments

    each comment is created by a user for another user and belongs to some user, or some comment

    my tables are

    CREATE TABLE `users` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `username` varchar(15) NOT NULL,
      `password` varchar(48) NOT NULL,
      `email` varchar(50) NOT NULL,
      `created_at` datetime DEFAULT NULL,
      `updated_at` datetime DEFAULT NULL,
      `deleted_at` datetime DEFAULT NULL,
      `deleted` tinyint(3) unsigned NOT NULL DEFAULT '0',
      PRIMARY KEY (`id`),
      UNIQUE KEY `username` (`username`),
      UNIQUE KEY `email` (`email`),
      UNIQUE KEY `id` (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    CREATE TABLE `comments` (
      `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
      `parent_id` int(10) unsigned DEFAULT NULL,
      `from_user` int(10) unsigned NOT NULL,
      `to_user` int(10) unsigned NOT NULL,
      `text` text NOT NULL,
      `updated_at` datetime DEFAULT NULL,
      `created_at` datetime DEFAULT NULL,
      `deleted_at` datetime DEFAULT NULL,
      `deleted` tinyint(3) unsigned NOT NULL DEFAULT '0',
      PRIMARY KEY (`id`),
      UNIQUE KEY `id` (`id`),
      KEY `parent_id` (`parent_id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

    i don’t know if i make any sense
    if you don’t understand tell me and i will try to make a better example

    how can i define the models for this situation ?
    how can i get all the comments for a user ?
    if i delete a comment that has children will the children be deleted ?

    best regards,
    ionut

  • #194 / Jan 26, 2012 8:51am

    toopay

    1583 posts

    @khavayero,
    There are at least two same reports, regarding those issue. But at this momment, i really dont have a time to do throughout test, related with that issue (and auto-time stamp issue in some place), due i am in a serious attemp to make most of PDO driver(s) fully working on CI, since latest version of Gas will rely (or at least i will recomend anyone to do so) on PDO. So, for now, you could use that factory method to hydrate a Gas instance instead instantiate it.

    @quasiperfect,
    At least, i could see a potential issue, with those schema. I probably will ended to this schema, for those task :

    # Note that each of gas model, could have more than one relationship type as long as different relationship type not pointing into same referal table.
    
      +--------+   +--------------+   +------------+
      | user   |   | comment_user |   | comment    |
      +--------+   +--------------+   +------------+
    +>| id     |<->| user_id      |   |            |
    | | name   |   | comment_id   |<->| id         |<-+
    | | ...    |   |              |   | parent_id  |<-+
    | +--------+   +--------------+   | .........  |
    |                                 | sender_id  |<-+
    |                                 +------------+  |
    +-------------------------------------------------+

    Read through documentation regarding how to set up those each relationship type.

  • #195 / Jan 26, 2012 9:48am

    quasiperfect

    132 posts

    @toopay thanks for responding

    not sure if i get your schema
    i will need 3 models ?
    or i need to define multiple relationships in user and comment ?

.(JavaScript must be enabled to view this email address)

ExpressionEngine News!

#eecms, #events, #releases