我有一個數據庫表名admin_menu與下面的模式 轉換笨查詢Laravel
CI中我使用的功能在我的模型獲得關聯數組導航(我可以輕鬆地重複和渲染菜單)如下
public function getMenuItems()
{
$st=$this->db->select('*')->from('admin_menu')->where('parent',0)->get()->result_array();
if(count($st)>0)
{
for($i=0;$i<count($st);$i++)
{
$st[$i]['child']=$this->db->select('*')->from('admin_menu')->where('parent',$st[$i]['id'])->get()->result_array();
}
}
else
{
return false;
}
return $st;
}
它給了我這樣的
Array
(
[menu] => Array
(
[0] => Array
(
[id] => 1
[name] => Users
[class] => icon icon-users
[url] =>
[parent] => 0
[child] => Array
(
[0] => Array
(
[id] => 2
[name] => Add
[class] =>
[url] => admin/add_user
[parent] => 1
)
[1] => Array
(
[id] => 3
[name] => Manage
[class] =>
[url] => admin/manage_users
[parent] => 1
)
)
)
)
)
多麼甜蜜的數組。現在在Laravel 5.2中,我爲admin_nav表創建了一個Model adminNav以及Migration,相同的數據庫模式。在我的控制器的索引功能,我用下面的代碼
public function index($name=NULL)
{
$adminNav=new adminNav();
$navs=$adminNav->all();
$parents=$adminNav->WHERE('parent',0)->get();
for($i=0;$i<count($parents);$i++)
{
$child=$adminNav->WHERE('parent',$parents[$i]['id'])->get()->toArray();
$parents[$i]['child']=$child;
}
return View('partials.form',[
'navs'=>$navs,
'parents'=>$parents,
]);
}
,我被一個巨大的參數列表懲罰我還沒有準備好一樣,我用指定者()函數來獲取此
Illuminate\Database\Eloquent\Collection Object
(
[items:protected] => Array
(
[0] => App\adminNav Object
(
[connection:protected] =>
[table:protected] =>
[primaryKey:protected] => id
[keyType:protected] => int
[perPage:protected] => 15
[incrementing] => 1
[timestamps] => 1
[attributes:protected] => Array
(
[id] => 1
[parent] => 0
[name] => Users
[url] =>
[updated_at] => 2017-03-04 05:47:07
[created_at] => 2017-03-04 05:47:07
[child] => Array
(
[0] => Array
(
[id] => 6
[parent] => 1
[name] => Add
[url] => adminController/add_user
[updated_at] => 2017-03-04 09:26:26
[created_at] => 2017-03-04 09:26:26
)
[1] => Array
(
[id] => 7
[parent] => 1
[name] => Manage
[url] => adminController/manage_users
[updated_at] => 2017-03-04 09:29:16
[created_at] => 2017-03-04 09:29:16
)
)
)
公告兒童和它完美的作品,並讓我在孩子的指數簡單數組但是當我嘗試使用相同的功能得到父母這樣
$parents=$adminNav->WHERE('parent',0)->get()->toArray();
,當它給我一個錯誤
我怎樣才能獲得結果的數組,而不是對象還是我問錯了問題?
毫無疑問,在Laravel中使用Eloquent永遠比查詢構建器更好。 –