mysql - 同一查询中 join 和 left-join 的两个语法问题

标签 mysql join laravel left-join

我有这个代码来创建一个集合:

$rank_entities_by_capacity = Entity::join('entity_capacitytypes', function($q){
     $q->on('entitys_id', '=', 'entities.id');
     $q->where('capacitytypes_id','=', '23');
 })->
leftJoin('user_attitudes', function($q){
                $q->on('entity_id', '=', 'entities.id');
                $q->where('item_type', '=', 'entity');
            })
            ->selectRaw('entities.*, SUM(user_attitudes.importance) AS importance')
            ->groupBy('entities.id')
            ->orderBy('importance', 'desc')
            ->take(6)
            ->get(); 

第一个问题:

1052 on 子句中的列“entity_id”不明确:

[2015-01-01 13:22:28] 生产。错误:致命数据库错误:500 = SQLSTATE[23000]:完整性约束违规:1052 on 子句中的列“entity_id”不明确(SQL:选择实体。 *, SUM(user_attitudes.importance) AS 重要性,来自 entities 内连接 entity_capacitytypes on entity_id = entitiesidcapacitytypes_id = 23 在 entity_id = entities 上左连接 user_attitudesid item_type = 按 entities.id 排序的实体组 importance desc limit 6) [] []

我花了一个多小时才找到绕过这个问题的技巧: 为了避免此错误,我被迫将表entity_capacitytypes中的列名称从entity_id(它导致问题)更改为entitys_id。 现在我的数据库名称不一致。还有其他方法可以避免该错误吗?

问题 2:

如果我将此部分添加到查询中,并尝试在 where 行中使用以前完美工作的变量

join('entity_capacitytypes', function($q){
     $q->on('entitys_id', '=', 'entities.id');
     $q->where('capacitytypes_id','=', $capacity);
 })->

我收到此错误: undefined variable :容量

如何让变量发挥作用?

我的解决方案:再次回避。

我无法修复连接,因此我使用了在Capacitytype模型中定义的关系:

    public function entities()
{
    return $this->belongsToMany('Entity', 'entity_capacitytypes', 'capacitytypes_id', 'entitys_id');
}

我从另一个模型访问实体,而不是使用 join

 $rank_entities_by_capacity = Capacitytype::find($capacity)->entities()->
leftJoin('user_attitudes', function($q){
                $q->on('entity_id', '=', 'entities.id');
                $q->where('item_type', '=', 'entity');
            })
            ->selectRaw('entities.*, SUM(user_attitudes.importance) AS importance')
            ->groupBy('entities.id')
            ->orderBy('importance', 'desc')
            ->take(6)
            ->get(); 

待办事项:

使变量在 join 中起作用

最佳答案

问题 1

要解决“不明确的列”问题,您只需指定包括表的完整列名

entity_capacitytypes.entity_id 而不是仅 entity_id

问题2

要在闭包(又称匿名函数)内使用像 $capacity 这样的局部变量,您需要使用 use 注入(inject)它们

join('entity_capacitytypes', function($q) use ($capacity){
    $q->on('entitys_id', '=', 'entities.id');
    $q->where('capacitytypes_id','=', $capacity);
})

关于mysql - 同一查询中 join 和 left-join 的两个语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27731533/

相关文章:

php - 这怎么能在mysql中完成?

mysql - 从 ACTUAL 值左连接 MIS-MATCH

join - 您对 Hadoop MapReduce 作业的建议

php - MySQL JOIN -> 从右表中获取所有数据,即使没有匹配项

laravel - 外键约束的格式不正确(Laravel 迁移)

Laravel - 在规则请求中验证今天之前 18 年前的出生日期

mysql - Laravel 迁移中的外键约束

PHP 脚本使服务器过载

mysql - 如何获得最大匹配输出

mysql - 对包含数字和其他非字母字符的 varchar 列进行排序