hope you're having a good day.
I'm using Laravel 8. I have three models and I need those models "entangled", so to speak.
So, I have three basic tables
areas,threats,positions
---
id
name
So the relationship needed is something like this:
t3 belongsToMany t1 and vice versa. (Many to Many)t3.t1 relationship belongsToMany t2 (Many to Many)My approach so far is this:
t3.t1).t3t1.t2).So far, the first relationship can be saved by doing $model->relatedModel()->attach($id);.
Now, for the second relationship, how can I attach the related models?
My last resort is to query the saved custom pivot model and attach the t2 model(s), but I wanted to ask first if there's a cleaner, eloquent-laravel way to do this.
Any advice would help. Thanks in advance for taking your time.
explanation
the attach method is actually a Model function. so with your withPivot t3.t1 is not a model yet
, when you are accessing with pivot magic method from your relation belongs to many it only return the column
answers
so for your situation, withPivot t3.t1 pivot as Model instance. here the steps
PivotModel that extends use Illuminate\Database\Eloquent\Relations\Pivot;t1Model, add using($classNamespace) to the belongsToMany method, example: belongsToMany()->using(PivotModel::class)t1->getT2s->pivot is already returning Model instance and you can use attach function to that pivotWhat I can think is 2 way one is just refer Spatie Laravel Role permission
In Spatie the relationship is like Many-to-many relationship between Permission and Role and Many-to-Many Polymorphic relationship mapping User, Role and Permission.
OR
Using extra attributes in many-to-many pivot relation.
somethinglike
return $this->belongsToMany('App\Role')->withPivot('column1', 'column2');
and attach and detach also accepts extra attributes.
$user->roles()->attach($roleId, ['expires' => $expires]);
while retrieving you can use where clause to specific your choice
return $this->belongsToMany('App\Role')->wherePivot('approved', 1);
I hope this will give you enough idea to implement it. all the snippet are from documentation, so you can directly search and refer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With