我有以下模型和相关的数据库表。 资源 标准 资源_标准
我已经正确地给了两个表 belongsToMany 并且所有的命名约定都是正确的。我正在尝试对查询进行联接,但我不断收到错误消息,指出我正在检查的字段不存在。因为我有几个值要检查,所以我将它们作为数组传递给查询生成器。以下是我构建查询的方式:
$resource = Resource::where(function($query) use($values)
{
if($values["grade"] != 0)
$query->where('grade_id', '=', $values["grade"]);
if($values['subject'] != 0)
$query->where('subject_id', '=', $values['subject']);
if($values['types'] != '')
{
if(is_array($values['types']) && count($values['types'])> 0)
$query->whereIn('resourcetype_id', $values['types']);
else
$query->where('resourcetype_id', '=', $values['types']);
}
if($values['standards'] != '')
{
if(is_array($values['standards']) && count($values['standards'])> 0)
{
$query->join('resource_standard', 'resource_standard.resource_id', '=', 'resource.id')
->with('standards')->whereIn('resource_standard.standard_id', $values['standards']);
}
else
{
$query->join('resource_standard', 'resource_standard.resource_id', '=', 'resource.id')
->with('standards')->where('resource_standard.standard_id', '=', $values['standards']);
}
}
})->distinct()->take(30)->get();
当有一个 standard_id 要检查时,会出现以下错误:
{
"error":{
"type":"Illuminate\\Database\\QueryException",
"message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'resource_standard.standard_id' in 'where clause' (SQL: select distinct * from `resources` where (`grade_id` = 2 and `subject_id` = 1 and `resource_standard`.`standard_id` in (4832, 4833)) limit 30)",
"file":"\/Users\/luke\/Dropbox\/DEV\/PHP\/4aplus\/4aplus\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connection.php","line":555
}
}
最佳答案
您也可以使用 Eloquent
模型加入
。只需使用以下代码:
$resource = Resource::join('resource_standard', 'resource_standard.resource_id', '=', 'resources.id')
取而代之的是:
$resource = DB::table('resources')->join('resource_standard', 'resource_standard.resource_id', '=', 'resources.id')
不要忘记在最后调用->get()
。
关于mysql - 使用 Eloquent 加入 Laravel 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23741649/