我有这个代码来创建一个集合:
$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
= entities
。id
和 capacitytypes_id
= 23 在 entity_id
= entities
上左连接 user_attitudes
。id
和 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/