2014-09-29 157 views
0

在经典的Rest API方法中,我的应用程序需要检查用户是否与某个帐户相关。我们可以对多个帐户执行操作,因此查询会在每个请求中执行。 由于这是我们最常称的查询,所以轻便对我的安宁至关重要。什么是Laravel的关于最轻量级查询的雄辩搜索?

当前的查询,使用机锋

$user-> accounts()-> where($primaryKey, $id); 

不知何故,这些都产生错误(雄辩的错误?)

$user-> accounts()-> find ($id); 
$user-> accounts()-> where ($primaryKey, $id)->count(); 

错误: SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'a_id' in where clause is ambiguous (SQL: select * from 'accounts' inner join 'users_accounts' on 'accounts'.'a_id' = 'users_accounts'.'a_id' where 'users_accounts'.'u_id' = 1 and 'a_id' = 1 limit 1)

回到我的问题,是有一个更优雅的解决方案,然后“where”功能?

回答

0

如果这是您最常用的查询之一,为何不缓存它?

$user->accounts()->where($primaryKey, '=', $id)->remember(60)->get(); 

所提到的查询失败,因为这两个表中具有相同名称的列

where 'users_accounts'.'u_id' = 1 and 'a_id' = 1 
+0

缓存确实下一步,欢呼声提醒。关于查询,那个是由Eloquent生成的,我知道它在哪里失败,然而我不确定为什么Eloquent会生成一个失败的查询。尽管如此,我不得不纠正你对最后一句话的意见。在哪里(列,值)是允许的:http://laravel.com/docs/4.2/queries – 2014-09-29 10:12:39

+0

是的,你是正确的,我总是使用这个参数的明确声明,因为它看起来更清晰。 – 2014-09-29 10:30:53

+0

你介意可靠地更新答案的语法部分吗?只是为了不混淆其他读者。 – 2014-09-29 13:19:11