mercredi 1 août 2018

I want to acquire the relation value with the store when searching for a category in Laravel5.6

thank you view my question.

I would like to retrieve information on the tag table relation with the store with many-to-many when searching for a category

I created Store-table, Category-table, Tag-table. The store-table and the category-table are connected by a many-to-many relation. The tag-table is the same.

I was able to search for categories and get information on businesses that are relation- ed, but I do not know how to get information on tags that are relations with stores.

So, I try this idea. search categories → get storeID from relation data→ storeID search → return shop data that hit. However, I do not know how to get storeID in the store data acquired by category search

How can I write the code? please help me.

sorry, bat my English.

App\Store

 use Illuminate\Database\Eloquent\Model;

 class Store extends Model
 {

  protected $fillable = ['name','location', 'price', 'open_time', 
  'closed_day'];
protected $table = 'stores';

public function photos(){
    return $this->hasMany(StorePhoto::class);
}

public function categories(){
    return $this->belongsToMany(Category::class,'category_store','category_id','store_id');
}

public function tags(){
    return $this->belongsToMany(Tag::class, 'store_tag', 'tag_id', 'store_id');
}

}

App\Category

protected $fillable = ['store_id', 'category_id'];

public function stores()
{
    return $this->belongsToMany(Store::class,'category_store','store_id','category_id');
}

App\Tag

protected $fillable = ['store_id', 'tag_id'];

public function stores()
{
    return $this->belongsToMany(Store::class, 'store_tag', 'store_id', 'tag_id');
}

Resource/Category

class Category extends JsonResource
 {
/**
 * Transform the resource into an array.
 *
 * @param  \Illuminate\Http\Request $request
 * @return array
 */
public function toArray($request)
{


    return [
        'id' => $this->id,
        'name' => $this->name,
        'store' => $this->stores,
    ];

}
}

web.php

use App\Category;
use App\Http\Resources\Category as CategoryResource;
Route::get("/store/api/category", function (Request $request) {
$search_category = $request->get('category_id');
return new CategoryResource(Category::find($search_category));
});



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire