不使用先前条件的子关系

时间:2016-02-06 06:44:56

标签: laravel laravel-4 laravel-5

我使用的是Laravel 4.我有以下型号:

class User extends Eloquent  {

    protected $table = 'users';

    public function questions()
    {
        return $this->hasMany('UserQuestion', 'user_id', 'user_id');
    }

}

class UserQuestion extends Eloquent  {

    protected $table = 'user_questions';

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

    public function subquestions()
    {
        return $this->hasMany('UserSubquestion', 'question_id', 'id');
    }

}

class UserSubquestion extends Eloquent  {

    protected $table = 'user_subquestions';

    public function question()
    {
        return $this->belongsTo('UserQuestion', 'question_id');
    }

    public function answers()
    {
        return $this->hasMany('UserAnswer', 'subquestion_id', 'id');
    }

}

class UserAnswer extends Eloquent  {

    protected $table = 'user_answers';

    public function subquestion()
    {
        return $this->belongsTo('UserSubquestion', 'subquestion_id');
    }

}

我有以下查询:

$results = User::with(['questions' => function($query) {
        $query->where('status', '1');
        $query->where('category', 'medicine');
    }])
    ->with('questions.subquestions', 'questions.subquestions.answers')
    ->get();

但是,我应用于where关系的questions条件未应用于已加入的表格subquestionsanswers

我如何才能使这些条件适用于他们?

注意:条件中statuscategory的值是动态的(即赢得1medicine)。

1 个答案:

答案 0 :(得分:0)

尝试像这样打电话:

$results = User::with(['questions' => function($query) {
        $query->where('status', '1');
        $query->where('category', 'medicine');
    },
    'questions.subquestions',
    'questions.subquestions.answers'
])->get();

注意,这次方法with只被调用一次。