Laravel 3表之间的5关系 [英] Laravel 5 relation between 3 tables

查看:69
本文介绍了Laravel 3表之间的5关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下3个表:usersrecipesvotes

I have these 3 tables: users, recipesand votes

用户对食谱进行投票

食谱有很多票

a recipe has many votes

用户有很多票

用户只能在食谱上投票一次

a user can only vote once on a recipe

在我看来,我遇到一个问题,当我尝试访问用户对以下配方的投票评分时:($recipe->user->vote->rating),它返回该用户的第一投票评分(可能是该用户的投票评分)用户使用其他食谱)

In my view i run into a problem, when I try to access the vote rating of a user on the recipe like:($recipe->user->vote->rating), it returns the first vote rating of that user (might be the vote of that user on another recipe)

我的关系是: User.php :

public function vote()
{
    return $this->hasOne('App\Vote');
}

Recipe.php :

public function votes()
{
    return $this->hasMany('App\Vote');
}

Vote.php :

public function user()
{
    return $this->belongsTo('App\User','user_id');
}

public function recipe()
{
    return $this->belongsTo('App\Recipe','recipe_id');
}

推荐答案

首先,我将使$user->votes具有hasMany关系,因为每个用户有多个投票.然后,您可以在vote模型上创建两个自定义查询范围:

First I would make $user->votes a hasMany relationship, since there are multiple votes per user. Then you can create two custom query scopes on the vote model:

User.php :

public function votes()
{
    return $this->hasMany('App\Vote');
}

Vote.php :

public function scopeByUser($query, $user_id){
    return $query->where('user_id',$user_id);
}

public function scopeOnRecipe($query, $recipe_id){
    return $query->where('recipe_id',$recipe_id);
}

这些可以像这样使用:

$recipe->votes()->byUser($id)->first();

$user->votes()->onRecipe($id)->first();

这篇关于Laravel 3表之间的5关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆