I have a problem to eagerload 2 relation in 1 table in laravel 9. i have table called photos have relation with users and photo_categories. so what i want to achieve is to load user and categories in same time.also im already declare the relation at the model.
what i already try is like code bellow
$photos = Photo::with('user','photoCategory')->where('id',$request->id)->first(); //at show method
$photos = new PhotoCollection(Photo::with('user','photoCategories')->OrderByDesc('id')->paginate(10));//at index method
my relation at Photo Model
public function user(){
return $this->BelongsTo(User::class);
}
public function photoCategory(){
return $this->HasMany(FotoCategory::class);
}
my relation at user model
public function photo(){
return $this->HasMany(PhotoCategory::class);
}
my relation at user photoCategory model
public function photo(){
return $this->BelongsTo(Photo::class);
}
please help me to figure out the problems
thankyou in advance
2
Answers
It looks like you have issues with your Photo model. The photoCategory method should be BelongsTo relationship:
In user model :
Here is final output relationship data :
Hope this will help you.
It looks like there is a typo in your code where you are calling photoCategories instead of photoCategory in the with method when eager loading the photoCategory relation.
Try updating your code like this:
Also, make sure that your PhotoCategory model has a belongsTo relationship to Photo model, like this: