简体   繁体   中英

Getting extra fields from laravel api having belongstomany relationship

I have two data tables related to each other by the belongstomany relationship. And when I am fetching data from its api controllers with selecting only two column keys ['id','title'] yet it returns some extra data in the response object.

model code:

public function place(){

    return $this->belongsToMany(Place::class,'city_place')->select(array('id', 'title'));

}

controller code:

public function ofcity($id)
{
    $city=City::findOrFail($id);
    return new CityResource(  $city->place()->get());

}

enter image description here

You must indicate the name of the table in front of the fields.

model Place code:

protected $columns = ['places.id', 'places.title']; //all column for select

public function scopeExclude($query, $value = [])
{
    return $query->select(\array_diff($this->columns, (array) $value));
}

model City code:

public function place()
{        
     return $this->belongsToMany(Place::class,'city_place', 'city_id', 'place_id');        
}

controller code:

public function ofcity($id)
{
    $cities = City::findOrFail($id)->place()->exclude(['featured_image'])->get()->toArray();
    return response()->json(['cities' => $cities], 200);    
}

In exclude skip all the fields that need not to be shown.

Thanks everyone here helping me out but none of the above solution worked..I figured it out after trying different functions and spending hours on this.

model Place code:

public function place(){

    return $this->belongsToMany(Place::class,'city_place','city_id','place_id')->select(array('places.id', 'places.title'));

}

controller code:

public function ofcity($id) { $city=City::findOrFail($id);

return new CityResource( $city->place()->get()->map(function ($item,$key) {

 return ['id' => $item['id'],'title'=>$item['title']];
    })

    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM