如何设置Laravel查询构建器返回的数组键?

时间:2014-04-25 23:46:06

标签: php laravel query-builder

我有两个表,pageedit

page

+----+-----------+
| id | page_name |
+----+-----------+
|  1 | page      |
+----+-----------+

edit

+----+---------+------+
| id | page_id | name |
+----+---------+------+
|  1 |       1 | home |
|  1 |       1 | side |
+----+---------+------+

现在我有一个关系定义将两者联系在一起。它返回如下内容:

array(
  'id' => 1,
  'page_name' => 'page',
  'edit' => array(
    0 => array(
      'id' => 1,
      'page_id' => 1,
      'name' => 'home'
    ),
    1 => array(
      'id' => 2,
      'page_id' => 1,
      'name' => 'side'      
    )
  )
)

我希望能够将edit数组的键设置为某列的值。像这样:

array(
  'id' => 1,
  'page_name' => 'page',
  'edit' => array(
    'home' => array( // the key is the name column
      'id' => 1,
      'page_id' => 1,
      'name' => 'home'
    ),
    'side' => array( // the key is the name column
      'id' => 2,
      'page_id' => 1,
      'name' => 'side'      
    )
  )
)

如何使用Laravel的查询构建器执行此操作?或者这是我必须要格式化的东西用循环手动结构?

2 个答案:

答案 0 :(得分:1)

一种解决方案

//the page you will work with
$page = Page::find(1);

//his edits, by pairs array('name' => 'id', ..)
$page_edit_lists = $page->edit()->list('id', 'name');    

//now, look for a name
$edit_name = 'grammar fix';
$edit_id = array_get($page_edit_lists , $edit_name); //if exist or null

//now get the row by is ID
$page_edits = $page->edit()->get();
//when edits data is already loaded, so it will loop for you..
$edit = $page_edits->find($edit_id);
//or by dynamic querying, SELECT .. WHERE id = ? ..
$edit = $page->edit()->find($edit_id);

没有测试过,但我认为你明白了。 还有我可怜的英语......

答案 1 :(得分:0)

http://laravel.com/docs/5.1/collections keyBy()。

  

$ collection = collect([       [' PRODUCT_ID' => ' prod-100',' name' => '台&#39],       [' PRODUCT_ID' => ' prod-200',' name' => '主席'],]);

     

$ keyed = $ collection-> keyBy(' product_id');

     

$ keyed->所有();

     

/ *       [           ' PROD-100' => [' PRODUCT_ID' => ' prod-100',' name' => '台&#39],           ' PROD-200' => [' PRODUCT_ID' => ' prod-200',' name' => '椅&#39],       ]   * /