【问题标题】:Join with Laravel 4 using Eloquent使用 Eloquent 加入 Laravel 4
【发布时间】:2014-07-07 15:26:58
【问题描述】:

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

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

【问题讨论】:

  • 你能展示你用来产生$values数组的相关代码吗? $values[foo] 是否有可能是 nullundefined
  • 这不可能,我取出连接并输出它正在生成的查询并且值在那里。只是由于某种原因无法识别加入。

标签: mysql join laravel laravel-4 eloquent


【解决方案1】:

您也可以使用Eloquent 模型join。只需使用以下代码:

$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()

【讨论】:

    【解决方案2】:

    我通过使用DB::table 而不是模型解决了这个问题。我猜你可能无法与模型进行连接。

    $resource = DB::table('resources')->join('resource_standard', 'resource_standard.resource_id', '=', 'resources.id')
    

    【讨论】:

    • 你可以对模型查询做同样的事情,错误说你在那里有错误的列名。
    • 正确,因为它无法识别连接。它没有看到连接的表,因此无法识别列。
    • 并不是它没有识别 - 模型查询是建立在您与 DB::table 使用的同一查询生成器上构建的,所以还有其他问题。
    猜你喜欢
    • 1970-01-01
    • 2022-10-04
    • 2014-11-21
    • 2014-04-17
    • 2015-01-27
    • 2018-08-16
    • 2022-01-13
    • 2014-11-30
    • 2013-02-04
    相关资源
    最近更新 更多