Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/255.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 是否可以使用Laravel';s Elount hasManyThrough()关系,还是需要原始数据库查询?_Php_Mysql_Laravel_Laravel 4_Eloquent - Fatal编程技术网

Php 是否可以使用Laravel';s Elount hasManyThrough()关系,还是需要原始数据库查询?

Php 是否可以使用Laravel';s Elount hasManyThrough()关系,还是需要原始数据库查询?,php,mysql,laravel,laravel-4,eloquent,Php,Mysql,Laravel,Laravel 4,Eloquent,我有三个数据库表:用户,问题和尝试: users - id questions - id - text attempts - id - users_id - questions_id - correct 每次用户尝试一个问题时,该问题的ID都会添加到尝试中。问题ID,他们的ID会添加到尝试中。用户ID 用户可以尝试任何次数的问题 目前,我可以通过以下功能检索用户的所有问题尝试: 在User.php模型中: public function attempts() { return $t

我有三个数据库表:
用户
问题
尝试

users
- id

questions
- id
- text

attempts
- id
- users_id
- questions_id
- correct
每次用户尝试一个问题时,该问题的ID都会添加到
尝试中。问题ID
,他们的ID会添加到
尝试中。用户ID

用户可以尝试任何次数的问题

目前,我可以通过以下功能检索用户的所有问题尝试:

在User.php模型中:

public function attempts()
{
    return $this->hasMany('Attempt', 'users_id');
}
我可以从test.php模型中得到一个尝试的问题,如下所示:

public function question()
{
    return $this->belongsTo('Question', 'questions_id');
} 
$user->correctAnswers; // collection of Question models with correct answer
$user->answers; // collection of Question models 

$user->answers->first()->pivot->correct; // returns 1 if the attempt was correct, otherwise 0 (suppose you have boolean/tinyint on that field)
我需要做的是让用户用雄辩的语言回答所有问题。我认为这可以通过使用
hasManyThrough()
来实现,但我不知道该怎么做(同时,为了便于说明,我已经大大简化了我的表格)

我希望能够做到这一点:

$answered_questions = User::answeredQuestions()->get();

你不能用hasManyThrough来做这个。 这是pivot table的多对多,此处为尝试,因此请使用:

// User model
public function correctAnswers()
{
    return $this->belongsToMany('Question', 'attempts', 'users_id', 'questions_id')
          ->wherePivot('correct','=',1)
          ->distinct();
}

public function answers()
{
    return $this->belongsToMany('Question', 'attempts', 'users_id', 'questions_id')
           ->withPivot(['correct']);
           ->distinct();
}
通过这种方式,您可以访问如下关系:

public function question()
{
    return $this->belongsTo('Question', 'questions_id');
} 
$user->correctAnswers; // collection of Question models with correct answer
$user->answers; // collection of Question models 

$user->answers->first()->pivot->correct; // returns 1 if the attempt was correct, otherwise 0 (suppose you have boolean/tinyint on that field)

通过回答问题,您的意思是正确=1?起初,我只想回答所有问题,不管这些问题是否正确(尽管基于这些问题进行选择的能力也很有用!)