【发布时间】:2019-10-18 19:13:51
【问题描述】:
我有三个表受益人,问题,响应..受益人
Benficiary
id name
1 user1
2 user2
3 user3
Questions
id question type
1 what is your hobby hobby
2 address contact
3 phone contact
..questions upto 500 and i need to select according to its type
Response
id beneficiary_id question_id response
1 1 1 football
2 1 3 5354353
3 2 1 basketball
4 3 2 cityname
5 3 3 432423
Beneficiary 表和 Question 表是静态的,但响应表连接了它们。我试图从 laravel 查询中做到这一点,但它只给了我回复 sql查询
select response,questions.question, beneficiarys.name
from responses RIGHT join (questions,beneficiarys)
on beneficiarys.id = responses.beneficiary_id && questions.id = responses.question_id
where questions.sheet_type = 'SCDS' OR questions.sheet_type = 'SMM'
laravel 查询
$beneficiaries = Beneficiary::with('quests','response')->whereHas('response', function ($query)use($sheet_type) {
$query->where('beneficiary_id', '>', 0);
})
->whereHas('quests',function($query)use($sheet_type){
$query->where('questions.sheet_type','=',$sheet_type);
$query->orWhere('questions.sheet_type','=','SCDS');
})
->where('updated_at','>=',!empty($this->request->from_date)?$this->request->from_date:$from)->where('updated_at','<=',!empty($this->request->to_date)?$this->request->to_date:$date)->get();
受益人模式
public function response()
{
return $this->hasMany('App\Model\Response');
}
public function quests(){
return $this->belongsToMany('App\Model\Question', 'responses','beneficiary_id','question_id');
}
问题模型
public function response(){
return $this->hasMany('App\Model\Response');
}
public function bens(){
return $this->belongsToMany('App\Model\Bebeficiary', 'responses','question_id','beneficiary_id');
}
响应模型
public function beneficiary(){
return $this->belongsTo('App\Model\Beneficiary', 'beneficiary_id');
}
public function question(){
return $this->belongsTo('App\Model\Question', 'question_id');
}
我需要根据其类型的所有问题(类型由用户从视图中选择),我需要这样的输出
beneficary hobby address phono ....
user1 football null 4244 ....
user2 basketball null null ....
有没有什么办法可以用sql或者laravel查询实现*
【问题讨论】:
-
你能发布 Eloquent 模型之间的关系吗?
-
一种解决方案是使用
querybuilder..连接表。另一种选择是使用关系概念... -
如果您在查询构建器中需要它,我可以在答案中发布它..
-
@jitheshjose 如果可以使用 querybuilder 那么请帮助我。