Relationships without id in Laravel

0

Good morning. I would like to relate two tables in Laravel, from the models, without using the id field.

That is, I have a table with a common field, which is not an ID. And I would like to relate them.

table 1 field 1 field 2 field a - > Field with the same value in the two tables

Table 2 field 3 field 6 field a - > Field with the same value in the two tables

Right now I use:

 class Device extends Model
{
  public function alarms()
{
    return $this->hasMany(Alarm::class, 'device_imei', 'device_imei');
}
}

But it does not work for me.

    
asked by Miguel Herreros Cejas 21.12.2017 в 18:30
source

1 answer

1

It should be something like that

public function alarms()
{
    return $this->hasMany('App\Alarm', 'foreign_key', 'local_key');
}

foreign_key : is the name of the foreign field of the model in which we are declaring.

local_key : is the name of the model field with which we are making the relation in this case 'App\Alarm' .

App \ Alarm : this is the model that we want to relate, notice that we passed it as string and adding namespace .

Then you can use this form:

$alarms = App\MiModelo::find(1)->alarms;

foreach ($alarms as $alarm) {
    //
}
    
answered by 28.12.2017 / 20:25
source