如何从avenirer / CodeIgniter-MY_Model中获取数据

时间:2016-01-19 19:14:39

标签: php string codeigniter foreach my-model-jami

这是我的category_model:

$this->has_many['details'] = array('foreign_model'=>'detail_category_m','foreign_table'=>'m_category_detail','foreign_key'=>'mcat_id','local_key'=>'mcat_id');

这是我的detail_category_model:

$this->has_one['category'] = array('foreign_model'=>'category_m','foreign_table'=>'m_category','foreign_key'=>'mcat_id','local_key'=>'mcat_id_detail');

我把这段代码放在我的CI控制器中:

$data['all']= $this->detail_category_m->with_category()->get_all();

一旦我foreach,我在视图中的var_dump()结果如下:

 object(stdClass)#32 (4) { ["mcat_id_detail"]=> string(1) "1" ["mcat_id"]=> string(1) "1" ["detail_cat_name"]=> string(5) "asdas" ["category"]=> object(stdClass)#35 (2) { ["mcat_id"]=> string(1) "1" ["cat_name"]=> string(7) "Travels" } } object(stdClass)#36 (4) { ["mcat_id_detail"]=> string(1) "2" ["mcat_id"]=> string(1) "1" ["detail_cat_name"]=> string(6) "asdsad" ["category"]=> object(stdClass)#37 (2) { ["mcat_id"]=> string(1) "2" ["cat_name"]=> string(7) "Voucher" } }

一旦我在视图中打印出来,就会产生如下结果:

stdClass Object ( [mcat_id_detail] => 1 [mcat_id] => 1 [detail_cat_name] => asdas [category] => stdClass Object ( [mcat_id] => 1 [cat_name] => Travels ) ) stdClass Object ( [mcat_id_detail] => 2 [mcat_id] => 1 [detail_cat_name] => asdsad [category] => stdClass Object ( [mcat_id] => 2 [cat_name] => Voucher ) )

一旦我在控制器中打印出这样的结果:

Array ( [0] => stdClass Object ( [mcat_id_detail] => 1 [mcat_id] => 1 [detail_cat_name] => asdas [category] => stdClass Object ( [mcat_id] => 1 [cat_name] => Travels ) ) [1] => stdClass Object ( [mcat_id_detail] => 2 [mcat_id] => 1 [detail_cat_name] => asdsad [category] => stdClass Object ( [mcat_id] => 2 [cat_name] => Voucher ) ) )

如何获取cat_name和mcat_id?

我做了这样的事情:

foreach($all as $row) :

echo $row->cat_name;

endforeach;

但它出错了;请帮助我如何获得我想要的数据。

2 个答案:

答案 0 :(得分:0)

试试这个

在视图中

foreach ($all as $value) {

    echo $value['cat_name'];
    echo "<br>";
    echo $value['mcat_id'];

}

答案 1 :(得分:0)

使用with _ *()方法时,必须提及要检索的字段:

$data['all']= $this->detail_category_m->with_category('fields:cat_name,mcat_id')->get_all();

现在,在您看来,您可以采取以下措施:

foreach($all as $detail)
{
  echo $detail->detail_cat_name;
  foreach($detail->category as $categ)
  {
    echo $categ->cat_name;
    echo $categ->mcat_id;
  }
}

希望这有助于......