How to get data from an intermediate table in an eloquent, Silex

I have created users , groups and group_user (MySQL) database tables. And the group_user table (staging table) contains user_id and role_id . there are a lot of users and groups. I want to delete a group in the groups table. Before deleting a group, I want to check if any user belongs to this group. I tried to do it this way.

Group.php (Model)

  public function users() { return $this->belongsToMany('\Modules\User\Models\User'); } 

Service.php

 public function deleteGroup($data) { if (!isset($data['groupID'])) return ['error' => 'Failed to delete group. Group id is required']; $group = Group::find($data['groupID']); if (!$group) return ['error' => 'Failed to delete group. Group not found']; // check any user belongs to group. $result = $group->users()->pivot->user_id; if(!$result){ $group->delete(); return ['success' => 'Successfully delete group.']; } return ['error' => 'Failed to delete group. Group not found']; } 

But that will not work.

+5
source share
1 answer

I will find out.

service.php

 public function deleteGroup($data) { $group = Group::find($data['groupID']); if (!$group){ return [ "msg" => "Failed to delete group. Group not found." ]; } // find out any one belongs to the group. $result = $group->users->first()->userID; if ($result){ return [ "msg" => "Failed to delete group. Group has users." ]; } $result = $group->delete($data['groupID']); if(!$result){ return [ "msg" => "Failed to delete group." ]; } return [ "msg" => "Successfully deleted group." ]; } 

This is how I do it. If there is another way, tell me. Thanks.

+3
source

Source: https://habr.com/ru/post/1241289/


All Articles