Laravel习俗关系

enter image description here

Very silly situation, The point is I can not change the database architecture because its a running e-commerce business having more then 1m active users.

Here is my situation.

Table User: Table Store:

Both have same primary key, mean we can call the one to one relation. But now I have to create belongs to many relation form Store to User.

store table have two columns

  1. slug
  2. parentId

Now I need to get all users having slug of store

So my query is

select * from users where id IN (select id from store where slug = ?);

How can I create a relation in this situation.

Hey there i would try to answer in detail as much as possible.

Create the following relationships:

For store:

public function users(){
   return $this->hasMany(User::class, 'id' ,'slug');
}

For user:

public function store(){
   return $this->belongsTo(Store::class);
}

Create a new controller and write a new function as below:

public function getStoreUsers(){
  $users = Store::where('slug','yourvalue')->firstOrFail()->users;
  return response()->json($users);
}

The function above will return a collection of users which have theirs 'id' equals to store 'slug'

In case if you have many stores you can do the follwing:

public function getStoreUsers(){
 $stores = Store::all();
 $storeUsers;

 foreach($stores as $store){
   $users = $store->users;
   $storeUsers[$store['id']] = array($users);
   return response()->json($storeUsers);
 }
}

This function will return an array of users of each store.

I have answered according to my understanding of your question if any erros occur please reply below so i can fix if possible. I Hope this is what you wanted if not let me know.

UPDATE:

This is what i could understand from your request.

Store a , store b , store c has slug = xyz. you have 50,000 users. 10,000 of them has slug xyz. and you need the information of those 10,000 users. if thats the case then the code below will help you out.

public function getStoreUsers(){
   $slugtomatch = 'xyz';
   $result;
   $stores = Store::where('slug',$slugtomatch)->get();

foreach($stores as $store){
   $users = $store->users;
   $result = array($users);
  }

return response()->json($result);

}

This will return an array of users those have the $slugtomatch value in their slug fields.