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

digitlimit's avatar

Eloquent HasMany relationships with multiple Columns

What is the best way to create this relationship?

The tables:
crawls table
- page_id
- date (dateTime)

elements table
- type
- value
- page_id
- added_on (dateTime)
- removed_on (dateTime)

The relation: A crawl can have many elements

WHERE crawls.page_id = elements.page_id AND (crawls.date = elements.added_on OR crawls.date = elements.removed_on)

How do you translate this into a HasMany relation?

 /**
     * Return both added and removed elements
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function elements() : HasMany
    {
        return $this->hasMany(Element::class, ..................);
    }
0 likes
1 reply
vincent15000's avatar

I'm not sure that it's possible to do this with a hasMany relationship where you have a these constraints.

You will probably have to write the query and access to the elements from a simple method returning a collection and not a relationship.

1 like

Please or to participate in this conversation.