I have 5 tables in my laravel/vue project:
- Movies
- Series
- Anime
- Actors
- Actors relationship
Actors' table belongs to Movies, Series, Anime and this many-to-many relationship is registered in the actors_relationship.
I'm able to create a many-to-many relationship in the Actor.php model using the following code:
public function movies() {
return $this->belongsToMany(MovieModel::class, "actors_relationship", 'actor_id', 'media_id')->wherePivot("media_type", AdminHelper::TYPE_MOVIES['value'])->withTimestamps();
}
Using this code I'm getting the records with the included actor id and has a specific int as a media_type.
Until this point, I have no problem. My problem is getting the count of all of these relationships. e.g. getting the count of movies, series, anime and sorting it desc/asc
Solutions:
-
Retrieving the relationship actors' count from movies, series, anime and register it in a custom
attribute. The sorting will be on the client-end. -
Doing a hard code check on the server-side for the sorting, then checking if the sort is by
total_count, if yes, then get the collection first and after the->get()command, try sorting by the customattribute.
I would like to follow the best practice regarding this issue. Is there a way to get the count of all relationships and sort by it?
A client-side solution would cause more work because this project will be for Android and Web and therefore will require various modifications in both fields.
Furthermore, I would normally do ->with('movies') and then sort the automatically created field movies_count. I would like to have a similar approach.
Tables:
actors:
id actor_title
movies:
id movie_title
series:
id series_title
anime:
id anime_title
actors_relationship:
id actor_id media_id media_type
EDIT:
I'm looking for the best advice to implement a total count of movies, series and anime. This means that I would like the total count of these 3 relations in one field. I could use a custom attribute, but then I will need to sort that using PHP/client-side instead of doing it in the SQL query in Eloquent.
This means that I'm looking for the best way that follows the best practices. The total_count will sum up the total of those aforementioned relations. I would like to sort by this new total_count.
from belongsToMany with multiple tables (design suggestion)
No comments:
Post a Comment