开发者

kohana ORM question

i am using kohana ORM in order to get some results from the database. My problem is: even though i have consulted the documentation, i can't find a way to select only the column i am interested in. To be more explicit, i have:

$sale_stock = Model::factory('product_type')
->where('product_type_id','=', $id )
-> find_all();

var dumping it, it selects me all the "SELECT product_type.* from product_type where etc". But i want to select only the 'stock' field from the salestock table. doing find('stock') instead find_all() returns a weired object... Where am i w开发者_StackOverflowrong, and how can i actually select only the column 'stock' using kohana orm?

thank you!


ORM methods find() and find_all() always select all table columns, so there is two ways to get specified fields:

  • Load full table rows and get columns from it:
$sale_stock = Model::factory('product_type')
   ->where('product_type_id','=', $id )
   -> find_all();
// get array of id=>stock values
$columns = $sale_stock->as_array('id', 'stock');
  • Create special method in model using Query Builder:
// model Model_Product_Type 
public function get_stocks($product_type_id) 
{    
   return DB::select(array('stock'))
      ->from($this->_table_name)
      ->where('product_type_id', '=', $product_type_id)
      ->execute($this->_db); 
}


I realise this isn't exactly what you're looking for, but I've pulled the following from the Kohana documentation ...

$articles = ORM::factory('article')->select_list('id', 'title');

foreach ($articles as $id => $title)
{
    // Display a list of links
    echo html::anchor('articles/'.$id, $title);
}

// Display a dropdown list
echo form::dropdown('articles', $articles);

You could think of it as a discount, two fields for the price of one.

It's common practice for ORMs to return a 'non-standard' object when partial model or merged model fields are requested. This prevents confusing operations using the original object (ie. how do you save an object when it contains only 2 of 8 fields, plus maybe some fields from another model?).

If you print_r the object, and give me an indication of how that looks ... it might be just what you want.


I know this is an old question, but i found maybe easier solution:

$sale_stock = ORM::factory('product_type')
   ->where( 'product_type_id','=', $id )
   ->find_all();
die($sale_stock->stock);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜