简体   繁体   English

Laravel 5.4-当模型有两个外来对象时如何获得正确的关系

[英]Laravel 5.4 - How I can get the correct relationship when model have 2 foreigns

I have 4 tables, 我有四张桌子

user_challenges user_challenges

  • id ID
  • challenge_id challenge_id
  • user_id 用户身份

user_scores user_scores

  • id ID
  • user_id 用户身份
  • challenge_id challenge_id

user 用户

  • id ID
  • name 名称

challenge 挑战

  • id ID
  • title 标题

How, in UserChallenge Model, I can get the user_scores value? 在UserChallenge模型中,如何获得user_scores值?

What is the correct relationship to can use in eagerloading. 可以在预先加载中使用正确的关系是什么。

I need something like this: 我需要这样的东西:

public function scores ()
{
return UserScore::where('user_id', $this->user_id)->where('challenge_id', $this->challenge_id);
}

I think you're missing the ->get() call from the end of your query. 我认为您在查询末尾缺少->get()调用。

Try: 尝试:

public function scores ()
{
    return UserScore::where('user_id', $this->user_id)->where('challenge_id', $this->challenge_id)->get();
}

There is no relationship (afaik) for your setup. 您的设置没有任何关系(afaik)。 You seek a relationship between 2 pivot tables, which is pretty uncommon. 您在2个数据透视表之间寻找一种关系,这种关系非常罕见。

You have 2 possibilities here in my opinion: 我认为您有两种可能性:
1) Merge them into 1 table 1)合并到一张桌子
2) user_scores should not have user_id and challenge_id, but one key user_challenges_id and should just be in a belongsTo relationship to user_challenges. 2)user_scores不应具有user_id和Challenge_id,而应具有一个键user_challenges_id,并且应仅与user_challenges属于归属关系。

There are 2 ways you can get the user_scores when using the UserChallenge Model. 使用UserChallenge模型时,有两种方法可以获取user_scores。 You can use a Query builder, like in your example. 您可以像示例中那样使用查询构建器。 You just need to add ->get(); 您只需要添加->get(); to that or it wont work. 否则将无法正常工作。

Secondly, you can use the relations you defined. 其次,您可以使用定义的关系。 Example: $userChallenge = UserChallenge::find(1); return $userChallenge->user->user_scores 示例: $userChallenge = UserChallenge::find(1); return $userChallenge->user->user_scores $userChallenge = UserChallenge::find(1); return $userChallenge->user->user_scores

If you have defined the relations properly every model can link to the next in a deeper level 如果您已正确定义关系,则每个模型都可以更深层次地链接到下一个模型

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

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