我有以下Model
,我不确定如何返回结果以便我可以选择所需的行,例如$this->model_name->function_name->function_value
- 还是有更好的方式?
型号:
function companyDetails()
{
$this->db->select('coreCompanyName, coreContactName, coreContactEmail');
$this->db->from('core');
$query = $this->db->get(1);
foreach($query->result() as $row)
{
echo $row->coreCompanyName;
}
return $query;
}
答案 0 :(得分:2)
通常,您可以将模型函数称为getCompanyDetailsByID()
,其中传递唯一标识符,并相应地返回单个结果对象:
<?php
function getCompanyDetailsByID($id)
{
$this->db->select('coreCompanyName, coreContactName, coreContactEmail');
$this->db->where('coreCompanyID', $id);
return $this->db->get('core')->first_row();
}
将“coreCompanyID”替换为您的主要列名。
<强>此外:强>
以下是您获取所有公司信息的方式:
<?php
function getCompanyDetails()
{
$this->db->select('coreCompanyName, coreContactName, coreContactEmail');
return $this->db->get('core')->result();
}
// And then in your controller:
function display()
{
$this->load->model('core');
$companies = $this->core->getCompanyDetails();
// Here's where you would probably load the data into a view
foreach ($companies as $company)
{
echo $company->coreCompanyName.'<br />';
}
}
最终答案! :P 强>
<?php
function companyDetails()
{
static $details;
if ( !$details)
{
$this->db->select('coreCompanyName, coreContactName, coreContactEmail');
$this->db->where('coreCompanyID', $id);
$details = $this->db->get('core')->first_row();
}
return $details;
}
现在你可以对该函数进行多次调用,它只会打到你的数据库一次,例如:
<?php
echo $this->core_model->companyDetails()->coreCompanyName;
// do stuff
echo $this->core_model->companyDetails()->coreContactName;
// more stuff
echo $this->core_model->companyDetails()->coreContactEmail;
所有这些只会打到你的数据库一次。