Home > Software engineering >  How to get properties from table C using model A through model B In laravel please?
How to get properties from table C using model A through model B In laravel please?

Time:10-25

I have 3 tables:

Table A - has only one phone

users
id | Name | phone_id
1 | Sam | 1
2 | Tom | 2

/**
* @return HasOne
*/
public function phone()
{
    return $this->hasOne(phones::class);
}

/**
* @return ???
*/
public function key()
{
    return ???;
}

Table B - has only one key

phones
id | Name | key_id
1 | Nokia | 1
2 | Samsung | 2

/**
* @return HasOne
*/
public function key()
{
    return $this->hasOne(keys::class);
}

Table C

keys
id | Name
1 | asd123
2 | qwe345

/**
* @return belongTo
*/
public function phone()
{
    return $this->belongTo(phones::class);
}

I wish to be able to get key from user model: User::find(1)->key()->Name.

Would you be able to help with that please?

CodePudding user response:

you need to work around hasOneThrough to get what you need.

let's break it down, based on your schema:

  • a User belongs to one Phone
  • a phone belongs to Key
  • therefore, a User belongs to Key through Phone

making this clear, we need to declare our key relationship inside the User model:

public function key()
{
    return $this->hasOneThrough(
        Key::class,       // model we are trying to get
        Phone::class,      // model we have an _id to
        'id',                 // WHERE `phone`.`id` = `user`.`phone_id`
        'id',                 // `key`.`id`
        'phone_id',        // local column relation to our through class
        'key_id'          // `phone`.`key_id`
    );
}

this will get you directly key from user

CodePudding user response:

You can build hasManyThrough() relationship in that case. Explained by example here Also read Docs

CodePudding user response:

Since a user can have only one phone (as mentioned) and phone has one key you have to use hasOneThrough() relation in model A.

Functions:

Public function getKey()
{
    Return $this->hasOneThrough(‘App\Models\Keys’, ‘App\Models\Phone’, ‘foreignKey on Phones’, ‘foreignKey on Keys’);
}

Note: For this to work you have to pick top to down approach so make migrations like this User->Phones->Keys.

There is another package that allow belongsToThrough i think its called haven’t used it tho if you want to look into reverse relation lookup (idk why someone need that :))

  • Related