[英]two syntax problems with join and left-join in the same query
我有以下代码来创建集合:
$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
上entity_id
= entities
。 id
和capacitytypes_id
= 23左连接user_attitudes
上entity_id
= entities
。 id
和item_type
通过=实体组entities
。 id
通过顺序importance
递减极限6)[] [ ]
我花了一个多小时进行交易,以找到绕过该问题的技巧:为了避免此错误,我被迫将表entity_capacitytypes中的列名从entity_id (这引起了问题)更改为entitys_id 。 现在我的数据库名称不一致。 还有其他避免错误的方法吗?
如果我将这部分添加到查询中,并尝试在where行中使用以前运行良好的变量
join('entity_capacitytypes', function($q){
$q->on('entitys_id', '=', 'entities.id');
$q->where('capacitytypes_id','=', $capacity);
})->
我收到此错误: 未定义的变量:容量
如何使变量起作用?
我的解决方案:再次避免。
我不会修复连接,所以我使用了Capacitytype模型中定义的关系:
public function entities()
{
return $this->belongsToMany('Entity', 'entity_capacitytypes', 'capacitytypes_id', 'entitys_id');
}
而不是使用连接,我从另一个模型访问了实体
$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();
使变量在联接中起作用
要解决“歧义列”问题,您只需要指定完整的列名(包括表)
entity_capacitytypes.entity_id
而不是仅entity_id
要使用像一个局部变量$capacity
封闭内(也就是匿名函数),你需要与他们注射use
join('entity_capacitytypes', function($q) use ($capacity){
$q->on('entitys_id', '=', 'entities.id');
$q->where('capacitytypes_id','=', $capacity);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.