我有一个Event
类和一个Question
类。这些形成了多对多关系。数据透视表还有一个asking
列。
我的数据库:
events (id)
questions (id)
event_question (id, event_id, question_id, asking)
我的活动课:
class Event {
public function questions() {
return $this->belongsToMany(Question::class)
->withPivot('asking');
}
}
例如,现在,我在数据透视表中可能有重复的“事件-问题”对,但是asking
数据透视列将有所不同。
id | event_id | question_id | asking
-----+------------+---------------+--------------
1 | 5 | 10 | 'purchaser'
2 | 5 | 10 | 'attendee'
我希望Eloquent提取两行,但只返回其中之一。
dd($event->questions->toArray());
// Should be 2 rows but there is only 1
[
[
'id' => 1,
'event_id' => 5,
'question_id' => 10,
'pivot' => [
'asking' => 'attendee', // asking 'buyer' is missing
],
],
];
答案 0 :(得分:0)
解决方案非常简单,我只需要指定哪些列是不同的:
class Event {
public function questions() {
return $this->belongsToMany(Question::class)
->withPivot('asking')
->selectRaw('DISTINCT questions.id, event_question.asking, questions.*');
}
}