Home > Back-end >  How to get data when foreign key value store as array?
How to get data when foreign key value store as array?

Time:09-22

I have two tables where the base user table id column as primary key and child table user_report has a foreign key user_id.

I know that this is not good way to store value as array. But i just want to know that for current scenario.

Table1: user

  • id
  • name
  • email

Table2: user_report

  • id
  • user_id ( value store as array like [1,2,4] )

Now the question is how can i easily retrieve user report data with user data with single qeury.

So far i have tried as below.

$report = UserReport::find( $id );
$users = User::whereIn( 'id', $report ->user_id )->get()->toArray();

I hope someone can help to solve this problem. Any suggetion would be appriciate.

CodePudding user response:

You can explode the user_id attribute to an array:

$users = User::whereIn( 'id', explode(',',$report ->user_id) )->get()->toArray();

CodePudding user response:

Try this kind of solution in your project. Because foreign key relation dont have multiple values like [1,2,3...] in one record.

Table1: user

id
name
email

Table2: report

id,
detail

Table3: user_report

id
report_id
user_id
  • Related