欢迎各位兄弟 发布技术文章
这里的技术是共享的
class Artist extends Eloquent implements SluggableInterface {
public function tags() {
return $this->belongsToMany('Tag', 'tag_artist');
}
ApiController:
class ApiController extends \BaseController {
public function getArtist() {
return Response::json(Artist::all());
}
}
It prints every single db column in a json format. My question is how can i output many to many relation object as an array?
E.g. every artist has many categories and vice versa. In a json page i am printing list of artists and their categories, like that:
[{
"id": 1,
"name": "someName",
"categories": [1, 2]
]}
@heihachi88 Just eager load the relation:
class ApiController extends \BaseController {
public function getArtist() {
return Response::json(Artist::with('tags')->get());
}
}
Thanks, but this way i won't get artists without tags? My output is:
[{"id":1,"title":"Danielle Pagac","image":"","text":"Ipsam","tags":[{"id":1,"title":"Prof. Treva Hoppe","pivot":{"artist_id":1,"tag_id":1}
}]
How can i display tags this way:
"tags": [1, 2]
I want to omit the rest tag columns.
If you're using PHP 5.5 or newer, you can do this:
$artists = Artists::with('tags')->get()->toArray();
$artists = array_map(function($artist)
{
$artist['tags'] = array_column($artist['tags'], 'id');
});
return Response::json($artists);
@thepsion5, i got php 5.5, but i get error:
syntax error, unexpected 'return' (T_RETURN)
Missing a bracket in the code.
$artists = Artists::with('tags')->get()->toArray();
$artists = array_map(function($artist)
{
$artist['tags'] = array_column($artist['tags'], 'id');
});
return Response::json($artists);
Yep, my bad. Edited my response now and fixed the syntax error.
Now i got another error :))
array_map() expects at least 2 parameters, 1 given
What should be in a callback?
@heihachi88 The best way to handle it is by using api transformers, that let you define the the way your resources are sent in your api. Otherwise you can define appends and hidden on the model or use in-line conversion like shown by @thepsion5 .
protected $hidden = ['tags'];
protected $appends = ['tagsIds'];
public function getTagsIdsAttribute()
{
return $this->tags->modelKeys();
}
This will hide tags collection from the json output, append tags_ids pseudo property that will hold the array from the accessor getTagsIdsAttribute.
@JarekTkaczyk thanks, but i am using Tag model in api also, if i hide title fields for artist json, then it won't show up in a tag json either..
@heihachi88 You didn't get the point. You hide tags collection in the artist model. It doesn't affect tag model in any way, so you will get it like usually.
@JarekTkaczyk aa, you mean to use this on Artist model. Let me try that.
@JarekTkaczyk thanks alot! Helped me.