Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

inyansuta's avatar

Pivot and next foreign key(s)

Hello, i have simple three tables (user, bookmaker and pivot table bookmaker_user).

In pivot table except standard columns (user_id, bookmaker_id) I also have several few columns, eg. a foreign key currency_id.

If I want get this value, I know, that in models I must have this:

// User model
public function bookmakers() {
    return $this->belongsToMany(Bookmaker::class)->withPivot('currency_id');
}

The question is: Is there any way that instead of id (number) in currency_id attribute gain equal access to the entire data object from a currencies table, like currency name?

Something like:

$user->bookmakers()->first()->pivot->currency->name

?

Thank for all answers.

0 likes
2 replies
SaeedPrez's avatar

I think it would be easier to do a separate query in this case.

inyansuta's avatar

Probably yes. Currently I am skipping solution using pivot and I have three models (one user can have more bookmakers and by one bookmaker can have different currency than the second user):

// User_Bookmaker.php / user_id, bookmaker_id, currency_id, next_foreign_ids...
public function user() {
    return $this->belongsTo(User::class);
}

public function bookmaker() {
    return $this->belongsTo(Bookmaker::class);
}

public function currency() {
    return $this->belongsTo(Currency::class);
}

// User.php
public function userBookmakers() {
    return $this->hasMany(User_Bookmaker::class)->with('currency');
}

// Bookmaker.php
...

The only drawback is a duplicate call user-->userBookmakers-->bookmaker, but I can call now:

// get currency name
$currency = User::find(1)->userBookmakers()->first()->currency->name

// get bookmaker name
$bookmakerName = User::find(1)->userBookmakers()->first()->bookmaker->name

If there is a better solution or above can be implemented using pivot, I'm grateful for the advice.

Please or to participate in this conversation.