laravel 3 way pivot - laravel

I've one many to many relationship between Entities and Affiliated Tables,
basically an affiliated can attend to many entities(example, medical services, dentist offices). One Entity can be visited by one or many affiliated.
Additionaly , one or more benefits can be occupied by one affiliated in a particular entity. As shown in the image.
I want to be able to answer queries like, which benefits where used by the affiliated in a particular entity.
Should i create a new Model, how should i rewrite the many-to-many relationship for ORM.
Thanks in advance!

Don't need a Affiliated_has_Entities model.
You could write the relationships as below, remember to check for arguments and its order in the belognsToMany relationship (sorry for misspelled words)
Entities model
public function afilliateds(){
return $this->belongsToMany('Afilliated', 'Afilliated_has_Entities');
}
Afilliated model
public function entities(){
return $this->belongsToMany('Entities', 'Afilliated_has_Entities');
}
public function benefits(){
return $this->belongsToMany('Entities', 'Afilliated_has_Entities');
}
Benefits model
public function entites(){
return $this->belongsToMany('Entities', 'Afilliated_has_Entities');
}
And so on..
I hope it helps

Related

How to implement a mutli-foreign key in laravel 8

I am working on a project where am required to implement a database relationship between tables(Trip, Truck, Fuel) . Below is the idea :
A truck has many trips
Each trip has many trucks
Each truck has got a fuel associated with a trip.
Now I was hoping to use Eloquent relationships to solve this but am stuck . How do I get a Fuel transaction and map it to a truck and trip ?
Thanks in advance !
you can use pivot table.
"pivot table is used to build a relationship between two tables where there is a Many to Many relationship."
in your case you can use Many to Many relationship between truck and trip then use fuel like a column in pivot table. it's easier
Eloquent does not support ternary relationships out of the box. This is because typically ternary relationships are incorrectly used when normal binary relationships would be more appropriate. For example I could argue that the Fuel entity is actually metadata on the Truck-Trip relationship and should be placed on the pivot table instead.
If you are completely 100% certain that your ternary relationship is correctly required then I think your best bet is to make a separate model TruckTrip i.e.:
class TruckTrip extends Model {
public function truck() {
return $this->belongsTo(Truck::class);
}
public function trip() {
return $this->belongsTo(Trip::class);
}
public function fuel() {
return $this->belongsTo(Fuel::class);
}
}
Then instead of relating Truck, Trip and Fuel directly you could use: hasManyThrough e.g.
class Trip extends Model {
public function trucks() {
return $this->hasManyThrough(Truck::class, TruckTrip::class);
}
public function fuel() {
return $this->hasManyThrough(Fuel::class, TruckTrip::class);
}
}
Similarly you can relate trucks to trips and fuel requirements and fuel requirements to trucks and trips
Laravel is offering many to many relationship but i prefer if you divided by tow relation.
make a table for this relation have the ID of truck and the ID of trips, then make a relation one to many between truck and this new table and another relation one to many between trip and this new table.
is will be easy for you

Nested eloquent relationship

I just started my first laravel project today and stumbled upon this confusing situation,
I intended to use eloquent relationship instead of manually joining tables on query. So here it goes...
I have 3 tables which are users , tbl_instruments_taught , tbl_instruments
users table does not hold any of the table's ID,
tbl_instruments_taught - holds the id of user and intruments
Note: user can teach multiple instruments
Now, I implemented a hasOne on my other result set but I dont think hasOne works on this one. I read about belongsToMany but as I try implement it, it seems like every minute, it gets confusing.
Any idea?
I think you are looking for pivot table and relation many to many.
You have users table, instruments table (user has many instruments and one instrument could belong to many users) and user_instruments pivot table. Here db model:
And then add belongsToMany relationship in User and Instrument model (with specified pivot table). Like so:
//IN USER MODEL
public function instruments()
{
return $this->belongsToMany('App\Models\Instruments', 'users_instruments', 'user_id', 'instrument_id');
}
//IN INSTRUMENT MODEL
public function users()
{
return $this->belongsToMany('App\Models\Users', 'users_instruments', 'insrument_id', 'user_id');
}
Now you can reach instruments/users data through laravel relations/eager loading.

Laravel Relationship with OR case

Assume I have a User model, and also I have Couple model which forms of 2 users, father_id and mother_id which are essentially user_ids
On User model, I have
public function kids() {
return $this->hasMany('App\Kid', 'father_id');
}
However, I want to check if user_id is either father_id or mother_id, return the related Kid model.
Is there a way to achieve it with a single relationship? What is the proper way of handling this scenario, so I can use $user->kids that would check for both cases?
There is a way, but you wouldn't typically use it to "check" if there are related models.
If you have a field that determines if the model is representing a father or mother, such as is_father, you could do:
public function kids()
{
return ($this->is_father)
? $this->hasMany(Kid::class, 'father_id')
: $this->hasMany(Kid::class, 'mother_id');
}
Essentially, the relationship method MUST return a relationship instance. But you can do logic before you return this.
NOTE: The relationship is cached, so even if the is_father value changes in the same thread run, it will utilize the same relationship that it did before. This can cause unwanted bugs.

Laravel / Eloquent - custom relation method

I have a class Report which has a belongsToMany relation to Metric. Report also additionally has a belongsTo relation to Metric.
Normally, the model returned by the belongsTo relation is the same as one of the models in the belongsToMany relation. When this is true I'd like it to be the case that each of the two relations actually looks at the same object instance (this also saves an extra trip to the db).
So, in basic terms - is there a way to get one relation to check another first, to see if a model has already been loaded, and if so, point to that object rather than creating a new one.
I tried putting some code in the belongsTo relation method for Metric but I can't get round the fact it needs to return an instance of belongsTo, which needs various things passed as constructor arguments (ie. a query object), which aren't relevant in that case that the model has already been loaded in the belongsToMany relation.
I thought of ditching the belongsTo relation and adding data horizontally in the pivot table for the belongsToMany relation, but it isn't a many-to-many relation required so that seems a bit wrong.
Thanks!
Geoff
The idea here is to write a function which would check if a relationship is loaded and return that relationship, otherwise it will return the belongsToMany. This would go in your Report class. This is also for Laravel 5. If you have 4, just remove the namespaces from the model names.
public function metric()
{
return $this->belongsTo('App\Metric');
}
public function metrics()
{
return $this->belongsToMany('App\Metric');
}
public function getMetric()
{
if(array_key_exists('metric', $this->getRelations())) {
return $this->metric;
}
return $this->metrics()->first();
}
If you do decide to just go with a belongsToMany only, I'd suggest putting a unique key on your pivot table for both ID's to keep from getting any duplicates in the pivot table.

Eloquent Eager Load Double Relationship

This one's been bothering me and Google hasn't been of any help. I have two models, a Dance model and an Author model. The relationship is that an author can have many dances. The wrinkle is that there are actually two relationships between these objects, as there is the original author and an author much later credited with reconstructing the dance (these are historical dances, after all). I can eager load with the load() function for the relation that uses the normal foreign key, but I cannot find out how to eager load the relation that uses a differently-named foreign key.
How do I do eager loading on this second relation?
When setting up a relationship with a different foreign key you have to specify in the relationship which key you wanna use...return $this->hasOne('Author', 'foreign-key');
So if I understand your question you wanna setup a relationship to two authors, in the same author table....
So maybe something like this then?? (replace foreign_key with your table field)
public function orig_author(){
return $this->hasOne('Author');
}
public function second_author(){
return $this->hasOne('Author', 'foreign-key');
}
public function dance(){
return $this->hasMany('Dance');
}
Then just retrieve it like so...($id being the id of your dance)
$dance = Dance::with('orig_author','second_author')->find($id);
But to be honest, I've never tried having a double relationship with a table.....let me know if it works out for you. :) Id be very interested.
You can do this:
$dance = ModelName::query()
->with('eagerNameOne')
->with('eagerNameTwo')
->find($id);
where ::query() was added only tu put all the eagers on the same identation level.

Resources