laravel 3个表之间的Laravel模型关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20721977/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 08:47:33  来源:igfitidea点击:

Laravel Model Relations between 3 tables

phplaraveleloquent

提问by madziikoy

I am currently trying to make a relation between 3 tables.

我目前正在尝试在 3 个表之间建立关系。

Users
    uid
    username
Groups
    gid
    groupname
GroupMembers
    uid
    gid

With eloquent ORM, how do I get the Groups of a User?
With just 1 line of query I wanted to return a json reply like: (search group that I am a member of... keyword: Admin)

使用 eloquent ORM,如何获取用户的组?
只需要 1 行查询,我就想返回一个 json 回复,例如:(我所属的搜索组...关键字:管理员)

Status 200
User   uid 1
       username mrwootwoot

       Groups
            {
             gid 1
             groupname administrators
            }
            {
             gid 2
             groupname wadmin
            }

What I got so far is:

到目前为止我得到的是:

$joined_networks = User::whereHas('groups', function($q)
{
    $q->where('is_blocked', '=', 0)->where('name','like',"%admin%");
})->with('groups')->where('uid', $user_id)->get();

(...)

return Response::json(array(
    'status' => 200,
    'user' => $joined_networks->toArray()
));

This part of the code is suppose to find the groups the user is a member of where he is not blocked.

这部分代码假设找到用户所属的组,他没有被阻止。



update

更新

$joined = User::with('group')->where('uid', $user_id)->get();

return Response::json(array(
    'status' => 200,
    'results' => $joined
));

and my user model:

和我的用户模型:

public function group()
{
    return $this->hasManyThrough('Group', 'GroupMembers', 'uid', 'gid');
}

Now it just returns nothing

现在它什么都不返回

{
    "status": 200,
    "results": {

    }
}


update

更新

$user = User::find($user_id);
$user_groups = $user->groups();

return Response::json(array(
    'status' => 200,
    'results' => $user_groups
));

But still the same as above, no result being given back.

但是还是和上面一样,没有返回结果。



updateIt was a mistake on the output. $user_groups->toArray() is the right one. Works well now.

更新这是输出错误。$user_groups->toArray() 是正确的。现在运作良好。

回答by Mark

How about something like this?

这样的事情怎么样?

in the user model put

在用户模型中放置

public function groups()
{
return $this->hasManyThrough('groups', 'GroupMembers', 'uid', 'id');
}

in the groups model put (not sure if this is necessary

在组模型中放置(不确定这是否有必要

public function users()
{
return $this->hasMany('GroupMembers', 'gid', 'id);
}

and then to get groups use

然后让组使用

return $this->user->groups

I got this from the laravel docs here http://laravel.com/docs/eloquent#has-many-through

我从这里的 laravel 文档中得到了这个http://laravel.com/docs/eloquent#has-many-through