php - 找不到 laravel 一对多关系列

标签 php mysql laravel laravel-4 eloquent

我有以下模型:

class Question extends Eloquent 
{
   public  function quiz()
   {
      return $this->belongsTo('Quiz','id_quiz','id');
   }
   public  function answer()
   {
      return $this->hasMany('Answer');
   }
}

class Answer extends Eloquent
{
   public function question()
   {
      return $this->belongsTo('Question','id_question','id');
   }
}

在我使用的 Controller 中:

$questions =  Question::with('answer')->whereHas(
     'quiz',  function($q) use($id) {$q->where('id', $id);
})->get();

我收到以下错误:

Column not found: 1054 Unknown column 'answers.question_id' in 'where clause' (SQL: select * from answers where answers.question_id in (10, 11, 12, 13)))

最佳答案

您应该以这种方式在您的Question 模型中定义您的answer 关系:

public  function answer(){
    return $this->hasMany('Answer','id_question','id');
}

因为正如您所说,您有列 id_question 而不是 question_id 在这种情况下什么是默认值。

关于php - 找不到 laravel 一对多关系列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29193203/

相关文章:

php - 如何防止用户删除记录

macos - OSX 上的 XAMPP 和 MySQL 安装

linux - Windows下无法运行Laravel Homestead(grep报错)

php - 布局在 Laravel 4 中抛出 "Attempt to assign property of non-object"

javascript - 使用 JavaScript 使用 API 时禁用 Laravel CSRF 保护/api 路由

php - PHP如何查找上一条SQL语句中创建的所有表的名称?

php - 无法访问特征中的 protected 属性

PHP 函数循环 SQL 结果并生成 HTML 表

php - 不能在一个查询中运行多个语句

mysql - 如何使用同一行上两列的值更新所有行中的单个列?