mysql - 使用 Eloquent 加入 Laravel 4

标签 mysql join laravel laravel-4 eloquent

我有以下模型和相关的数据库表。 资源 标准 资源_标准

我已经正确地给了两个表 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/

相关文章:

sql - 混合左连接和右连接?为什么?

php - 如何在 Laravel 5.5 中动态设置 SSH key ?

php - 服务器删除和保留输入类型文件的区别

mysql - 向表添加主键是否会检查默认列?

管理开发环境中mysql无法启动

PHP SQL 一次从表单更新一行

PostgreSQL 中的 SQL JOIN - WHERE 子句中的执行计划与 ON 子句中的执行计划不同

Python os.path.join Linux 上的绝对路径

php - SSL3_GET_SERVER_CERTIFICATE :certificate verify failed using xampp on mac

php - Laravel Lumen - 日志 channel