简体   繁体   English

Laravel与数据透视表的关系

[英]Laravel relationship with pivot table

I have 3 tables in my database : 我的数据库中有3个表:

users (id);
interests (id);
users_interests (user_id, interests_id);

I want to be able to fetch all the user's interests in this way : 我希望能够以这种方式获取用户的所有兴趣:

$interests = $user->interests

This is what I wrote in the User.php model, following laravel's doc: 这是我在laravel的文档之后在User.php模型中写的:

public function interests() { 
    return $this->hasManyThrough(
         'App\Interest', 'App\UserInterest', 
         'user_id', 'id', 'interest_id'
    );
}

but it returns empty even though the user has a game. 但即使用户有游戏,它也会返回空。 So there has to be something I'm doing wrong 所以一定是我做错了

Anyone to help me ? 有人帮我吗?

I think a belongs to many would do the job: 我认为一个belongs to many会做的工作:

public function interests() { 
    return $this->belongsToMany(
         'App\Interest', 
         'users_interests', 
         'user_id', 
         'interests_id'
    );
}

Quite similar to the example in the docs 文档中的示例非常相似

If you were to rename users_interests table to interest_user and the column interests_id to the singular form you would just need the first parameter: 如果你要重命名users_interestsinterest_user和列interests_id以单数形式,你会只需要第一个参数:

 public function interests() { 
        return $this->belongsToMany(App\Interest::class);
    }

From my understanding the hasManyThrough is used to jump forward within a relation (also described in the docs): 根据我的理解, hasManyThrough用于在一个关系中跳转(在文档中也有描述):

The "has-many-through" relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. “具有多次通过”关系为通过中间关系访问远处的关系提供了方便的快捷方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM