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

andreich1980's avatar

Relation on two columns

Hello everyone.

I have 3 tables in my DB: tables, columns, descriptions.

Table hasMany columns.

return $this->hasMany(Column::class, 'object_id', 'object_id');

Both tables and columns can have a record in descriptions table. For Table the relation is descriptions.major_id = tables.object_id AND descriptions.minor_id = 0. For Column the relation is descriptions.major_id = columns.object_id AND descriptions.minor_id = columns.column_id.

This is how descriptions for tables and columns work is Microsoft SQL Server.

How to build proper relationships?

For Table it is

public function description()
{
    return $this->hasOne(Description::class, 'major_id', 'object_id')
        ->whereMinorId(0);
}

For Column it would be

public function description()
{
    return $this->hasOne(Description::class, 'major_id', 'object_id')
        ->whereMinorId(
            $this->column_id /* <--- what should I put here? */
        );
}

$this-column_id returns 0. Actually dd($this) returns an empty Column object.

P.S. I'm thinking about creating relation "Table hasMany ColumnDescriptions" and then I'll "connect" 2 collections $table->columns and $table->columnDescriptions.

P.P.S. Found an issue https://github.com/laravel/framework/issues/5355 and Tailor said he won't implement composite keys functionality :/

P.P.P.S. Well, it would work if I don't use with('description'). But it's then N+1 problem, for each column I show it makes one request to get the description.

I also tried to rid of the relations at all and to add a global scope with custom join but it failed when I use a paginate method. So I also needed a custom pagination.

0 likes
0 replies

Please or to participate in this conversation.