For n-level deep have you looked at some of the nested set packages for laravel?
Model Relationships not yielding desried result
So guys, i need some help. First of all, i would like to thoroughly understand defining relationships using eloquent. My situation is that i have a category model that is n-level deep. I also have services that belongs to a category irrespective of its depth.
Below is my category 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 addons()
{
return $this->hasMany(AddOn::class);
}
public function timeslots()
{
return $this->hasMany(TimeSlot::class);
}
public function banners() {
return $this->hasMany(Banner::class);
}
public function partnerservices() {
return $this->hasMany(PartnerService);
}
}
And Here is my PartnerService Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class PartnerService 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',
'service_description'
];
public function category() {
return $this->belongsTo(Category::class, 'category_id');
}
public function booking() {
return $this->hasMany(Booking::class);
}
public function ratings()
{
return $this->hasMany(Rating::class);
}
}
Now when i query the relationship from a first level category i.e a category that has no parent then i can get the partner services using the "with['partnerservices']" in my controller. However when i try to do the same with a category that has a parent, this returns as empty, even when the service belongs to a category.
Please or to participate in this conversation.