Kohana ORM custom methods in models

I have two models:

  class Model_user extends ORM {
     protected $ _has_many = array ('credits', array ('model' => 'credit', 'foreign_key' => 'user'));
 }

 class Model_credit extends ORM {
     protected $ _belongs_to = array ('user', array ('model' => 'user', 'foreign_key' => 'user'));
     protected $ _tb = 'credits';
     protected $ _pk = 'id'; 
     // method to be implemented
     public function total () {
         return $ total_credits_available;
     }
 }

 // accessing the 'total' method
 $ user = ORM :: factory ('user', 1);
 $ total_credits = $ user-> credits-> total ();

The point is how to implement the "total" method, which does something like:

  return DB :: select (array (DB :: expr ('SUM (qty * sign)'), 'total'))
     -> from ($ this -> _ tb)
     -> where ('user', '=', $ user_id)
     -> execute ()
     -> total;

The method counts user loans (this can be + loans and -loans) and return the total amount of available loans. While I am using the ORM :: factory method to create a custom object, I would like to implement the "total" method in such a way that it uses the loaded resources, rather than starting a new request (I wrote the above request to demonstrate business logic).

Any suggestions?:)

+4
source share
1 answer
<?php class Model_user extends ORM { protected static $_totals = array(); protected $_has_many = array('credits', array('model'=>'credit', 'foreign_key'=>'user')); public function total() { $total = Arr::get(Model_User::$_totals, $this->id, FALSE); if ($total !== FALSE) return $total; return Model_User::$_totals[$this->id] = $this->credits ->select(array(DB::expr('SUM(qty * sign)'), 'total')) ->find() ->total; } } 
+6
source

Source: https://habr.com/ru/post/1337774/


All Articles