Laravel Eloquent的关系 - hasOne?

时间:2017-09-25 15:29:39

标签: laravel eloquent

我有一个带有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

我是否混淆了这些关系?

1 个答案:

答案 0 :(得分:0)

通过Attaching a hasOne model to another Laravel/Eloquent model without specifying id

解决方案

更新为问题模型:

public function type()
{
    return $this->belongsTo(QuestionType::class, 'type_id');
}

添加到QuestionType模型:

public function questions()
{
    return $this->hasMany(Question::class, 'type_id');
}