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');
}
Related
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
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 a ManyToMany relationship between Election and Party to connect parties to multiple elections.
public function parties(): BelongsToMany
{
return $this
->belongsToMany(Party::class)
->using(ElectionParty::class)
->withPivot('has_no_answers', 'published', 'program_pdf', 'program', 'id');
}
On the pivot table election_party I added an auto incrementing id.
Parties can give answers to each election, for which reason I created a hasMany relationship to Answer on the pivot table, referenced by electionparty_id
class ElectionParty extends Pivot
{
public function answers(): HasMany
{
return $this->hasMany(Answer::class);
}
}
Now, to get the answers or in this case it's count, i do this in Blade:
#foreach($election->parties as $party)
{{ $party->pivot->answers->count() }}
#endforeach
This however, does not work, because it does not try to get answers by the pivot table id, which I assumed it would be but by the id of the election:
SQLSTATE[42703]: Undefined column: 7 ERROR: column answers.election_id does not exist LINE 1: select * from "answers" where "answers"."election_id" = $1 a... ^ HINT: Perhaps you meant to reference the column "answers.question_id". (SQL: select * from "answers" where "answers"."election_id" = 16 and "answers"."election_id" is not null)
Am I missing something here or doing something not how it's supposed to be done?
The default keys are generated differently in pivot models. Specify the foreign key:
class ElectionParty extends Pivot
{
public function answers(): HasMany
{
return $this->hasMany(Answer::class, 'electionparty_id');
}
}
i have two tables as below:
users table:
|id|name|email|password|created_at|updated_at
messages table:
|id|sender_id|receiver_id|message|created_at|updated_at
User model:
public function threads()
{
return $this->hasManyThrough(Message::class, User::class,'id','sender_id');
}
i'm trying retrieve message threads
which isn't working. any help appreciated.
This is an example from laravel eloquent relationship
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
can you review your code
It seems that you want to retrieve all messages that belongs to a single thread (list of users) using hasMany relationship Through User model, to do that You have to define hasManyThrough inside Thread model not in User model, here is an example:
User:
|id|name|email|password|created_at|updated_at|thread_id
Note thread_id foreign key because thread is a list of users
Thread:
class Thread extends Model {
public function messages() {
return $this->hasManyThrough(Message::class, User::class,'thread_id','sender_id', 'id', 'id');
}
}
Example from laravel doc
I have 3 tables:
users
-id
-name
relation_types
-id
-type
user_relation
-user1_id
-user2_id
-relation_type_id
In User model I have:
public function relatedParties()
{
return $this->belongsToMany('App\User', 'user_relation', 'user1_id', 'user2_id')->withPivot('relation_type_id');
}
I can get the relation_type_id by App\User::find(1)->relatedParties[0]->pivot->relation_type_id.
In order to get relation type instead of id, I added this relationship in the model of user_relation table
public function type()
{
return $this->belongsTo('App\RelationType', 'relation_type_id');
}
but App\User::find(1)->relatedParties[0]->pivot->type returns null
Any thoughts would be appreciated.
You can use Nested Eager Loading
$user=User::with('relatedParties','relatedParties.type')->first();
foreach($user->relatedParties as $relatedParty)
{
foreach($relatedParty->type as $type)
{
print_r($type->type);
}
}
You can't access type from pivot table because type is not a column in the proviot table. so your code for access type is giving null for acessing type.
App\User::find(1)->relatedParties[0]->pivot->type
Again relationship in user_relation table is between relation_types, user_relation table which can not be called in the realtion of users,user_relation.
To get the type of "relation_type_id" just simply get the type from relation_types table as written below.
$relationTypeId = \App\User::find(3)->relatedParties[0]->pivot->relation_type_id;
$rtype = \App\RelationType::find($relationTypeId)->pluck('type');
echo $rtype;