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

catalin8's avatar

How to model a hasMany relationship with an extra condition ?

I have a Category model with parent, children relations

The problem is my Category table holds multiple hierarchies from different websites and due to the nature of the project, I don't have a parent_id to uniquely point to a category, so I rely on this structure that adds an extra condition to the relations (parent.website = children.website):

Website     Category      Parent
A           1             null
A           2             1

Can I do this for relationships:

public function children() {
    return $this->hasMany(Category)->where('website', $this->website);
}

And how do I create the migration to reflect it in terms of indexes ?

0 likes
7 replies
catalin8's avatar
Schema::create('categories', function (Blueprint $table) {
	$table->bigIncrements('id');
	$table->string('website', 100);
	$table->string('hierarchy');
	$table->string('parent_hierarchy')->nullable();

	$table->timestamps();
});

Where hierarchy is the full category: Books>Crime>Short Novel And Parent hierarchy: Books>Crime. This is Website A

For Website B, I may have: Monitors>Led>4K

So I need to create a hasMany relation. And the added difficulty is the extra condition that the parent and child share the same website.

kalemdzievski's avatar

So let me check if I understood u right. U are trying to write a relationship for children that will generate the following query:

SELECT * FROM category WHERE website = 'website_parent'; 
catalin8's avatar
SELECT * FROM
	category categories
LEFT JOIN
	category children
ON
	categories.hierarchy=children.parent_hierarchy
AND
	categories.website=children.website
catalin8's avatar

Thank you, I'll look into it, but not optimal for me, so I'll do it using plain SQL queries. I thought there may be a Eloquent way to achieve it.

catalin8's avatar

But seem you are right on this one. On that plugin it explicitly says:

Eloquent doesn't support composite keys. As a consequence, there is no way to define a relationship from one model to another by matching more than one column.

And gives exactly what I need as example.

Please or to participate in this conversation.