HasOneThrough eloquent relationship in Laravel.

HasOneThrough
What is “HasOneThrough” eloquent relationship?

Laravel introduces a relationship: “HasOneThrough”. This is new in Laravel Development but, other framework uses this like “Rails”.

The “HasOneThrough” relationship links models through a single intermediate relation. For example, if each group will have users and users will have their users history. Then the group model may access the users history through the user.

If we look into the database,
1. groups: id, user_id
2. users: id
3. user_history: id, user_id

Why we have to use “HasOneThrough” eloquent relationship?

The history table does not contain a group_id column. Now, if I want to get the detail of user, I will write code like:
$groups→users→userHistory.
The “HasOneThrough” relation can provide the access to the users history to the group model. Now, you can use the “HasOneThrough” relationship to skip this step, accessing the users detail straight away like:
$usersdetail=$groups→userHistory.

How to use “HasOneThrough” eloquent relationship?

namespace App;

use Illuminate\Database\Eloquent\Model;
 
class Group extends Model
{
    /** Get the user's history. */
    public function userHistory()
    {
        return $this->hasOneThrough('App\History', 'App\User');
    }
}

The first argument passed to the “HasOneThrough” method is the name of the final model we wish to access, while the second argument is the name of the intermediate model.


class Supplier extends Model
{
    public function userHistory()
    {
        return $this->hasOneThrough(
            'App\History',
            'App\User',
            'group_id', // Foreign key on users table...
            'user_id', // Foreign key on history table...
            'id', // Local key on groups table...
            'id' // Local key on users table...
        );
    }
}

Typical eloquent foreign key conventions will be used when performing the relationship’s queries. If you would like to customize the keys of the relationship, you may pass them as the third and fourth arguments to the “HasOneThrough” method. The third argument is the name of the foreign key on the intermediate model. The fourth argument is the name of the foreign key on the final model. The fifth argument is the local key, while the sixth argument is the local key of the intermediate model.