[英]How to get data from intermediate table in eloquent, silex
I created database tables users
, groups
, and group_user
(MySQL).And group_user
table (intermediate table) contains the user_id
and role_id
. 我创建了数据库表
users
, groups
和group_user
(MySQL)。而group_user
表(中间表)包含user_id
和role_id
。 users and groups relationship is many to many. 用户和群体的关系是多对多的。 I want to delete a group in
groups
table. 我想删除
groups
表中的groups
。 Before deleting a group, I want to check if there is any user belongs to that group. 在删除组之前,我想检查是否有任何用户属于该组。 I tried to do it this way.
我试着这样做。
Group.php (Model) Group.php(型号)
public function users()
{
return $this->belongsToMany('\Modules\User\Models\User');
}
Service.php 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 this doesn't work. 但这不起作用。
I find it out. 我发现了。
service.php 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 please tell me.
如果还有其他方式请告诉我。 Thanks.
谢谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.