简体   繁体   English

在内部关系中使用JOIN

[英]Using JOIN inside relation

I have three tables: Tournaments, Participants, Users. 我有三个表:锦标赛,参与者,用户。 The structure is: 结构为:

Tournaments: 比赛:

-Id
-Description
-Date

Participants 参加者

-Id
-Id_tourn
-Id_user

Users 用户数

-Id
-Name

On my blade template I need all the info from Tournaments table and info of the User which is the participant of that tournament. 在我的刀片模板上,我需要锦标赛表中的所有信息以及该锦标赛的参与者用户的信息。

I've created the relation between Tournaments and User Models. 我已经创建了锦标赛和用户模型之间的关系。

UPDATE: Tournaments Model: 更新:锦标赛模型:

public function users() {
   return $this->belongsToMany('App\User', 'Participants', 'Id_tourn', 'Id_user');
}

public function getTournaments()
{
    return $this->with('users')->get();
}

Tournament Controller: 比赛控制器:

public function show()
{
    $tourns = new Tournaments();

    $tournaments = $tourns->getTournaments();
    return $tournaments;
}

but when I try $tournament->users in foreach loop it returns 0 results 但是当我在foreach循环中尝试$tournament->users ,它返回0个结果

Thanks a lot! 非常感谢!

It seems you are using a One to Many relationship on a Many to Many case, here are the documentation of the Many to Many relationship. 似乎您在“多对多”案例中使用“多对多”关系, 是“多对多”关系的文档。 You need to make a relationship like this: 您需要建立这样的关系:

public function users() {
    return $this->belongsToMany('App\User', 'Participants', 'Id_tourn', 'Id_user');
}

So you will can access users like this: 因此,您可以像这样访问用户:

$tournament->users

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

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