Apr 12, 2022
0
Level 1
Relationship between category and product
I have a nested category, n-level deep. Some categories have children and others don't. I want to be able to add products to a category such that when i query the product model i should be able to access the products related to that specific category.
I want to be able to use the result as json and access the products in the result.
My challenge here is that when i call the relation ship, the product is attached to the top level category even though it belongs to a category n-level deep.
Here's my Category and Product Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
'title',
'subtitle',
'category_id',
'img',
'video',
'status',
];
public function parent()
{
return $this->belongsTo(Category::class, 'category_id');
}
public function children()
{
return $this->hasMany(Category::class, 'category_id');
}
public function product() {
return $this->hasMany(Product::class);
}
}
Product Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'image',
'video',
'title',
'discount',
'time_taken',
'max_quantity',
'price',
'status',
'which_to_show',
'category_id',
'sub_category_id',
'child_category_id',
'product_description'
];
public function category() {
return $this->belongsTo(Category::class, 'category_id');
}
public function ratings()
{
return $this->hasMany(Rating::class);
}
}
Product Controller
<?php
namespace App\Http\Controllers\Api\General;
use App\Http\Controllers\Controller;
use App\Models\PartnerService;
class ProductAPIController extends Controller {
public function category_services () {
$product = Product::select([
'id',
'image',
'video',
'title',
'discount',
'time_taken',
'max_quantity',
'price',
'status',
'which_to_show',
'category_id',
'sub_category_id',
'child_category_id',
'service_description'
])->with('category')
->orderBy('title', 'asc')
->get();
$response = [
'product' => $product
];
return response()->json($response, 200);
}
}
Please or to participate in this conversation.