初めまして。拝見していただきありがとうございます。
使用環境
Laravel5.6
MacOS X
PHP 7
現在Laravel5.6にてカテゴリーを検索するとそれに紐付いたお店情報とお店情報に付随したタグ情報が帰ってくるAPIを作成しております。
カテゴリーのIDを検索すると、カテゴリー名とお店情報を取得することはできたのですが、お店と結びついているタグ情報をどう一緒に取得取得したいのですがどうすれば一緒に取得できるのかわかりません。
教えていただけますと嬉しいです。
Model
Store
1 2protected $fillable = ['name','location', 'price', 'open_time', 'closed_day']; 3 protected $table = 'stores'; 4 5 public function photos(){ 6 return $this->hasMany(StorePhoto::class); 7 } 8 9 public function categories(){ 10 return $this->belongsToMany(Category::class,'category_store','category_id','store_id'); 11 } 12 13 public function tags(){ 14 return $this->belongsToMany(Tag::class, 'store_tag', 'tag_id', 'store_id'); 15 }
Category
1protected $fillable = ['store_id', 'category_id']; 2 3 public function stores() 4 { 5 return $this->belongsToMany(Store::class,'category_store','store_id','category_id'); 6 }
Tag
1class Tag extends Model 2{ 3 protected $fillable = ['store_id', 'tag_id']; 4 5 public function stores() 6 { 7 return $this->belongsToMany(Store::class, 'store_tag', 'store_id', 'tag_id'); 8 } 9}
App/Resources
Category
1class Category extends JsonResource 2{ 3 /** 4 * Transform the resource into an array. 5 * 6 * @param \Illuminate\Http\Request $request 7 * @return array 8 */ 9 public function toArray($request) 10 { 11 return [ 12 'id' => $this->id, 13 'name' => $this->name, 14 'stores' => 15 [ 16 'store' => $this->stores, 17 こちらにお店に紐付いたタグの情報を取得したいです 18 ], 19 ]; 20 21 } 22}
Route
web
1use App\Category; 2use App\Http\Resources\Category as CategoryResource; 3Route::get("/store/api/category", function (Request $request) { 4 $search_category = $request->get('category_id'); 5 return new CategoryResource(Category::find($search_category)); 6});
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/08/08 06:50