我的数据库里有三张桌子。候选人,评委和分数。
现在,我要做的是去获取、查询或显示那些还没有被评委打分的候选人。
在基本php中,我们可以使用sql查询来查询,如
select * from scores where candidateId='1' and judgeId='2'
有谁能帮我解决拉勒维尔雄辩的关系?
发布于 2017-11-10 09:11:40
对于这个简单的查询,您不需要雄辩的关系,只需使用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传递到视图并在视图中获得分数,但不建议在视图中执行查询。我的意思是不要打电话给候选人::找到(1)在你的观点,但$候选人->分数可以做内视图。
https://stackoverflow.com/questions/47218527
复制相似问题