John Davidson

php - Laravel relationship with 2 keys

0 comments
Message:


I have a table of measurements and a conversions to which is used to convert, say, cm into m.


My conversion table has the columns id, from, to, calculation, where from and to are database ids of my units.


I want to use a Laravel relationship to get the conversion data from my measurement model.


The keys I would like to join on are:


measurements.unit_id -> conversions.from
measurements.display_unit_id -> conversions.to

I can use a BelongsTo relationship but it seems limited to only join on one key, not two as I would like.



My Answer:
conversions.from_unit_id and conversions.to_unit_id.

To set up this relationship in Laravel, you can define it in your Measurement model like this:

php
public function conversionFrom()
{
return $this->belongsTo(Conversion::class, 'unit_id', 'from_unit_id');
}

public function conversionTo()
{
return $this->belongsTo(Conversion::class, 'unit_id', 'to_unit_id');
}


This code defines two relationships in the Measurement model: conversionFrom and conversionTo. These relationships specify that the Measurement model belongs to the Conversion model based on the unit_id and either the from_unit_id or to_unit_id in the Conversion model.

You can then access the conversion data for a measurement like this:

php
$measurement = Measurement::find(1);
$fromConversion = $measurement->conversionFrom;
$toConversion = $measurement->conversionTo;


This will retrieve the conversion data for the measurement based on the from_unit_id and to_unit_id in the Conversion model.

Rate this post

3 of 5 based on 3804 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us