php - Eager Load lists() in Laravel 4 -


in laravel 4 use eager loading manytomany relationship:

public function categories() {      return $this->belongstomany('category');  } 

it returns categories this:

    "categories": [         {             "id": 1,             "priority": 1,             "title": "my category 1",             "created_at": "2013-08-10 18:45:08",             "updated_at": "2013-08-10 18:45:08"         },         {             "id": 2,             "priority": 2,             "title": "my category 2",             "created_at": "2013-08-10 18:45:08",             "updated_at": "2013-08-10 18:45:08"         }     ], 

but need this:

    "categories": [1,2] // references category id's 

the query builder has method called "lists" should trick. it's not working in case of eager load???

public function categories() {      return $this->belongstomany('category')->lists('category_id');  } 

the reason doesn't work because when eager-loading it, using with method, laravel expects relationship method return illuminate\database\eloquent\relations\relation object, can call get on it. when call lists, query ran , returned instead array.

what do, reduce data transferring, use select method on query, , run lists on categories collection. example:

model.php

function categories() {     return $this->belongstomany('category')->select('id'); } 

whatever.php

$posts = post::with('category')->get(); $categories = $posts->categories;  // list ids $categoriesids = $categories->lists('id'); 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -