kohana ORM问题

dan*_*ana 5 orm select kohana

我正在使用kohana ORM以从数据库中获得一些结果.我的问题是:即使我已经查阅了文档,我也找不到只选择我感兴趣的列的方法.为了更明确,我有:

$sale_stock = Model::factory('product_type')
->where('product_type_id','=', $id )
-> find_all();
Run Code Online (Sandbox Code Playgroud)

var转储它,它选择我所有的"SELECT product_type.*from product_type where etc".但我想从salestock表中只选择'stock'字段.做find('stock')而不是find_all()返回一个weired对象......我哪里错了,我怎样才能真正选择使用kohana orm的'stock'列?

谢谢!

bia*_*ron 5

ORM方法find()find_all()始终选择所有表列,因此有两种方法可以获取指定的字段:

  • 加载完整的表行并从中获取列:
$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');
Run Code Online (Sandbox Code Playgroud)
  • 使用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); 
}
Run Code Online (Sandbox Code Playgroud)