0

I have two tables, page and edit.

page

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

edit

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

Right now I have a relationship defined linking the two together. It returns something like this:

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'      
    )
  )
)

I would like to be able to set the key of the edit array to the value of a certain column. Like so:

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'      
    )
  )
)

How can I do this using Laravel's query builder? Or is this something I'll have to format & structure manually with a loop?

2
  • You have to manually build this after the query returns the data. Commented Apr 26, 2014 at 0:28
  • Too bad, but I do understand, as it can get complicated... Commented Apr 26, 2014 at 23:54

2 Answers 2

1

One solution

//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);

Didn't test it, but i think you get the idea. And sory for my poor english..

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That's close to what I did; not exactly, but it works!
0

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

$collection = collect([ ['product_id' => 'prod-100', 'name' => 'desk'], ['product_id' => 'prod-200', 'name' => 'chair'], ]);

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

$keyed->all();

/* [ 'prod-100' => ['product_id' => 'prod-100', 'name' => 'Desk'], 'prod-200' => ['product_id' => 'prod-200', 'name' => 'Chair'], ] */

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.