[英]Laravel Eloquent relationships - hasOne?
我有一個問題表,其中有一個type_id列。 此處定義的值與QuestionTypes模型有關。
問題表:
--------------------------
| id | title | type_id |
--------------------------
| 1 | apple? | 2 |
| 3 | banana? | 2 |
| 4 | kiwi? | 2 |
| 5 | pear? | 3 |
--------------------------
QuestionTypes
----------------
| id | title |
----------------
| 1 | multi |
| 2 | single |
| 3 | free |
----------------
在問題模型中,我有:
public function type()
{
return $this->hasOne(QuestionType::class);
}
我想從questiontypes表中打印標題,但是當我嘗試使用$question->type->title
在視圖中輸出時,得到:
Column not found: 1054 Unknown column 'x__questiontypes.questions_id' in 'where clause'
(SQL: select * from `x__questiontypes` where `x__questiontypes`.`questions_id` = 2 and `x__questiontypes`.`questions_id` is not null limit 1
我有沒有把感情弄混?
通過將hasOne模型附加到另一個Laravel / Eloquent模型而不指定id的解決方案
更新為問題模型:
public function type()
{
return $this->belongsTo(QuestionType::class, 'type_id');
}
添加到QuestionType模型:
public function questions()
{
return $this->hasMany(Question::class, 'type_id');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.