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

uloncl's avatar

two columns on a table refering to the id on another table relationship

table A -table_a_id -foo_id -bar_id ...

table B -table_b_id

foo_id and bar _id are both foreign keys refering to table bs id, how can i represent this relationship in the eloquent model for table a

0 likes
1 reply
Dunsti's avatar

Just make a seperate function for each relation and add the fieldnames:

in A-Model:

public function foo()
{
    return $this->belongsTo(B-Model::class, 'id', 'foo_id');
}

public function bar()
{
    return $this->belongsTo(B-Model::class, 'id', 'bar_id');
}

In B-Model:

public function foo()
{
    return $this->hasMany(A-Model::class, 'foo_id', 'id');
}

public function bar()
{
    return $this->hasMany(A-Model::class, 'bar_id', 'id');
}

Please or to participate in this conversation.