Laravel 5 如何更改方法类orm Laravel中的键id?
可能是不可能的,但我在表格中有无线电输入的答案,id为问题和答案,如id=36,答案=Yes。我下面的代码得到了所有答案Laravel 5 如何更改方法类orm Laravel中的键id?,laravel-5,eloquent,Laravel 5,Eloquent,可能是不可能的,但我在表格中有无线电输入的答案,id为问题和答案,如id=36,答案=Yes。我下面的代码得到了所有答案 public function getAnswer() { return $this->hasMany('App\Answer', 'user_id', 'id') ->with('question') ->whereHas('question.group', function($query)
public function getAnswer() {
return $this->hasMany('App\Answer', 'user_id', 'id')
->with('question')
->whereHas('question.group', function($query) {
$query->where('name', 'simple_quesion');
});
}
我有收藏,没问题
#items: array:9 [▼
0 => getAnswer {#400 ▶}
1 => getAnswer {#401 ▶}
2 => getAnswer {#402 ▶}
但是,是否有任何方法可以通过此集合获取密钥并进行分配
#items: array:9 [▼
35 => getAnswer {#400 ▶}
37 => getAnswer {#401 ▶}
42 => getAnswer {#402 ▶}
在这个方法中,公共函数getAnswer
[更新]
全套
Collection {#396 ▼
#items: array:9 [▼
0 => getAnswer {#400 ▼
#fillable: array:3 [▶]
#connection: "mysql"
#table: null
#primaryKey: "id"
#keyType: "int"
+incrementing: true
#with: []
#withCount: []
#perPage: 15
+exists: true
+wasRecentlyCreated: false
#attributes: array:7 [▼
"id" => 18
"user_id" => 11
"answer_id" => 34
"answer" => "YES"
]
#original: array:7 [▶]
#changes: []
我需要关键答案_id=>34
#items: array:9 [▼
34 => getAnswer {#400 ▼
试试这个:
在应答模型中,添加以下内容:
public function question(){
return $this->belongsTo("App\Question"); //the column name of the question should be "question_id"
}
在问题模型中,请执行以下操作:
public function answers(){
return $this->hasMany("App\Answer");
}
在控制器中,您只需执行以下操作即可获得问题及其答案:
Question::with('answers')->all(); //assuming you want to get all the questions and their answers
希望我的回答有帮助 好吧,我太傻了。这太容易了。在刀片或控制器中,我可以使用:
{{ dd($user->getAnswer->pluck('answer', 'answer_id')) }}
你能展示一个集合项目的外观吗?好的,我用完整集合更新了。如果我理解正确,你想恢复一个问题及其所有答案吗?就这样?是的,我想避免创建另一个foreach。我想这样做,当我得到这个数据的方法。