我的数据库中有 3 个表。候选人、评委和分数。
现在,我想做的是获取、查询或显示尚未被评委评分的候选人。
在基本的 php 中我们可以使用 sql 查询来查询
从candidateId='1'和judgeId='2'的分数中选择*
任何人都可以帮助我如何在 Laravel Eloquent 关系上做到这一点吗?
最佳答案
对于这个简单的查询,你不需要 Eloquent Relationship,只需使用 Model 即可:
$scores = Score::where(['candidateId' => 1, 'judgeId' => 2])->get();
但是如果您想使用关系来做到这一点,您必须首先在分数模型中定义关系:
class Score extends Model {
protected $table = 'scores';
public function candidate() {
return $this->belongsTo(Candidate::class, 'candidateId');
}
public function judge() {
return $this->belongsTo(Judge::class, 'judgeId');
}
}
然后您可以通过关系进行查询:
$candidateId = 1;
$judgeId = 2;
$scores = Score::whereHas('candidate', function($query) use ($candidateId) {
$query->where('id', $candidateId);
})->whereHas('judge', function ($query) use ($judgeId) {
$query->where('id', $judgeId);
})->get();
更新#1: 如果您想获得每个候选人的分数,您可以在候选人中定义关系:
class Candidate extends Model {
protected $table = 'candidates';
public function scores() {
return $this->hasMany(Score::class, 'candidateId');
}
}
然后找到候选人及其分数:
$candidate = Candidate::find(1);
$scores = $candidate->scores;
您可以将 $candidate 传递给您的 View 并在 View 中获取分数,但不建议在您的 View 中进行查询。我的意思是不要在 View 内调用 Candidate::find(1),但 $candidate->scores 可以在 View 内完成。
关于php - Laravel Eloquent 2 个表与 1 个表相关的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47218527/