Laravel 5表之间的关系

时间:2016-02-24 21:43:43

标签: laravel-5

我有以下3个表:usersrecipesvotes

用户对食谱投票

  

食谱有很多票

     

用户有很多选票

     

用户只能对食谱投票一次

在我看来我遇到了一个问题,当我尝试访问食谱上的用户的投票评级时:($recipe->user->vote->rating),它返回该用户的第一个投票评级(可能是投票该用户在另一个食谱上)

我的关系是: 的 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');
}

1 个答案:

答案 0 :(得分:0)

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

<强> 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();
相关问题