I have 3 models: Movie, Celebrity, Role. Each movie has many celebrities and each celebrity has many roles in many movies (for example the movie "Once Upon a Time" has celebrity "Quentin Tarantino" as roles ["Director","Writer"], and obviously "Quentin Tarantino" can have other movies performing different roles.
What is the best way to implement a many-to-many relationship between these 3 models, where we can easily access each movie's staff directly (like $movie->$roles->director)
Should we define a pivot table with movie_id, celebrity_id, role_id and a primary key of (movie_id, celebrity_id, role_id)?
class Movie extends Model{
public function movieCelebrityRole()
{
return $this->hasMany(MovieCelebrityRole::class);
}
}
class Celebrity extends Model{
public function movieCelebrityRole()
{
return $this->hasMany(MovieCelebrityRole::class);
}
}
class Role extends Model{
public function userRoleCompany()
{
return $this->hasMany(MovieCelebrityRole::class);
}
}
class MovieCelebrityRole extends Model{
public function movie()
{
return $this->belongsTo(Movie::class);
}
public function celebrity()
{
return $this->belongsTo(Celebrity::class);
}
public function role()
{
return $this->belongsTo(Role::class);
}
}
If you get a pivot table with more than two Foreign Keys, or have multiple many-to-many relationships, try to treat it as full model.
This also helps you to define more simple relationships.
Instead of Many-to-Many relationship. You can divide it into multiple of One-to-Many relationships.
E.g: In your case, you're going to have 4 models : Movie, Celebrity, Role, Program.
Movie hasMany Program.
Celebrity hasMany Program.
Role hasMany Program.
Program belongsTo Movie.
Program belongsTo Celebrity.
Program belongsTo Role.
For more details, check the Laravel documentation about the One-to-Many relationships :
https://laravel.com/docs/8.x/eloquent-relationships#one-to-many
Related
I have a users table, a products table, and and an assets table. A user can have many assets, as can a product, meaning both Users, and Products have a 1:n relationship with assets. In Laravel how would show this relationship in Eloquent, is this a Polymorphic relationship, with the struct of the assets table columns being something like,
ID, type, file_path, ownable_id, ownable_type
I think your assets table columns should be
id, type, file_path, assetable_id, assetable_type
Add this relation to your user and product model
public function assets()
{
return $this->morphMany(Asset::class, 'assetable');
}
Next, add this relation to your asset model
public function assetable()
{
return $this->morphTo();
}
relation of user model
public function assets()
{
return $this->morphMany(Asset::class, 'assetable');
}
relation of asset model
public function assetable()
{
return $this->morphTo();
}
I have two models which are connected each other.
class Company extends Model {
public function addresses() {
return $this->belongsToMany('\App\Address', 'address_mapping', 'uid_company', 'uid_address');
}
}
class Address extends Model {
}
In my JOIN table I have a column named active. How can I fetch all active addresses from the company? Or how can I implement a where-clause in the JOIN table?
Thank you!
The table that you call a "JOIN table", usually called a pivot table.
You can fetch all active records by using wherePivot method:
$company = Company::first();
$activeAdresses = $company->addresses()->wherePivot('active', 1);
Or you can directly define the relationship in your model:
class Company extends Model {
public function activeAddresses() {
return $this->belongsToMany('\App\Address', 'address_mapping', 'uid_company', 'uid_address')
->wherePivot('active', 1);
}
}
See section Filtering Relationships Via Intermediate Table Columns in Eloquent documentation
i have a hasManyTrough() relation in my database but could not get it to work with eloquent.
the relation in my database
category(id)
entry(id)
category_entries(category_id, entry_id)
i have 3 models
Category
has_many CategoryEntries
Entry
has_many CategoryEntries
CategoryEntry
belongs_to Category
belongs_to Entry
so every category has many entries and every entry has many categories.
in rails i would do the following
Entry
has_many CategoryEntries
has_many Categories, through: :category_entries
i have created the following in eloquent
CategoryEntry
public function category(){
return $this->belongsTo('App\Category');
}
public function entry(){
return $this->belongsTo('App\Entry');
}
Category
public function categoryEntries(){
return $this->hasMany('App\CategoryEntry');
}
Entry
public function categoryEntries(){
return $this->hasMany('App\CategoryEntry');
}
public function categories()
{
return $this->hasManyThrough('App\Category', 'App\CategoryEntry', 'category_id', 'id');
}
but this will create the following sql command:
select `entries`.*, `category_entries`.`category_id` from `entries`
inner join `category_entries` on `category_entries`.`id` = `entries`.`entry_id`
this makes no sence. where is my mistake?
As described in your question, relation is
Category (hasMany) Entry (hasMany) CategoryEntries
So we can add hasManyThrough relation in Category Model not in Entry model
class Category
.......
public function categoryEntries()
{
$this->hasManyThrough(App\CategoryEntry::class, App\Entry::class);
}
UPDATE
if the relation is based on db you have given, then you have Many-Many relation between Category and Entry. then you can have,
class Entry
....
public function categories()
{
return $this->belongsToMany(App\Category::class, 'category_entries');
}
I have three tables, one of them is pivot table (and pivot model) and trying to create belongsTo relationship in pivot model (foreign key in pivot table) so that I can get the relevant name from some other table(has primary key). What I want to do is illustrating by images below:
Pivot Table is:
And other table is:
It is pivot Model:
class MproductIngredient extends Model {
public function qtyType() {
return $this->belongsTo('App\TIngredientType','priQuantityTypeNo');
}
}
How to get the relevant name from other table(has primary key).
My code is:
#foreach($prd->ingredients a $ingredient)
"{!! $ingredient->pivot->priQuantityTypeNo !!}"
#endforeach
Please describe more as far i understand you can make below to relationships
for belongstoMany
public function qtyTypes()
{
return $this->belongsToMany('App\TIngredientType', 'pivot_table_name',
'main_table_id', 'TIngredientType_id');
}
for hasOne
public function qtyType()
{
return $this->hasOne('App\TIngredientType');
}
I have an object Tournament and 2 relations:
A tournament belongs to a user ( the admin who created it)
A tournament hasMany users ( Competitors )
I can distinct one from other with his role ( Admin, competitor )
Can I do that, or should I get conflicted???
If not, how should I do it???
You can do this - you just need to define 2 relations for your Tournament object, e.g.:
class Tournament extends Model {
public function admin() {
return $this->belongsTo(User::class, 'admin_id');
}
public function competitors() {
return $this->belongsToMany(User::class);
}
}
Your tournament-admin relation key will now be stored in admin_id field of your tournaments table, while tournament-competitor mapping will be stored in user_tournament table - make sure you have one.
You can read more about operating on many-to-many relationships here: http://laravel.com/docs/5.1/eloquent-relationships#many-to-many