State what you expect and what you already tried
Although I moved onto something else at that time, I really do need to make this working now; has anyone faced this problem and found how to do it?
jarektkaczyk said:
State what you expect and what you already tried
I just want to know how I have to declare this on my Model files and how to use it (find(), save(), ...).
Cheers,
Alright, I have this working.
There a two approaches here. The first is easy: Make the pivot table a regular table with a model and use easy belongsTo
and hasOne
relationships. But that's no fun (and it falls apart when you want to use it like a pivot table, as you then have to deal with hasManyThrough
relations... -.-).
So, we'll do a three-way and use withPivot
and wherePivot
to access the third wheel on each relation:
In the Currency
model:
public function land_fee_types()
{
return $this->belongsToMany('LandFeeType', 'currencies_land_fee_types_versions')->withPivot('version_id');
}
public function versions()
{
return $this->belongsToMany('Version', 'currencies_land_fee_types_versions')->withPivot('land_fee_type_id');
}
In the LandFeeType
model:
public function currencies()
{
return $this->belongsToMany('Currency', 'currencies_land_fee_types_versions')->withPivot('version_id');
}
public function versions()
{
return $this->belongsToMany('Version', 'currencies_land_fee_types_versions')->withPivot('currency_id');
}
And in the Version
model:
public function currencies()
{
return $this->belongsToMany('Currency', 'currencies_land_fee_types_versions')->withPivot('land_fee_type_id');
}
public function land_fee_types()
{
return $this->belongsToMany('LandFeeType', 'currencies_land_fee_types_versions')->withPivot('currency_id');
}
No that we have this setup, we can query it:
$currencies = Currency::all()->land_fee_types()->wherePivot('version_id', 3)->get();
By doing this, each object in $currencies
now has a pivot
object that includes the pivot data:
$first_version_id = $currencies->first()->pivot->version_id;
Hope this helps! ;)
First of all, thanks for your lenghtly reply! Secondly, I gave up on this and I just used the first option you described, as your second option is way too "hacky" I think and not 100% trustable in terms of results (I already have the 'value' field as a pivot), but thanks for mentionning it!
Cheers,
@sisou, your question should be cast in stone! I was looking for this for centuries :D What about, if we had 4(,5,6,...) columns?
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community