A quiet hum
A quiet hum

Reputation: 93

Laravel Eloquent Relationship with a comma separated field

I have inherited a DB with 2 tables I need to link, a users table and a us_states table. The users table has a field called states_visited and it's a comma-separated field (for instance, New York, Alabama and Texas would be stored as 8, 2, 41). I want to define a hasMany relationship, but unfortunately find_in_set(states.id, users.states_visited) does not work since Laravel queries both tables separately so they don't "see" each other during the Query.

Any help resolving this would be amazing.

Upvotes: 1

Views: 3023

Answers (2)

GhanuBha
GhanuBha

Reputation: 1

I have created custom relationship constraints to solve this.

My First Package | ReadMe

OR you can also add this package by using,

composer require ghanuz/relations

I have tested only with select clause not with insert/update using associates functionality.

But it can be helpful.

Upvotes: 2

Kjartan
Kjartan

Reputation: 310

If you want to use Laravel relationships you will have to refactor to use a Many to Many relationship. Your other option is to use MySQL find_in_set function but then to write your own logic for it.

Upvotes: 0

Related Questions