在经典的Rest API方法中,我的应用程序需要检查用户是否与某个帐户相关。我们可以对多个帐户执行操作,因此查询会在每个请求上执行。由于这是我们最常被称为查询的问题,它的轻松对我的心灵平静很重要。
当前查询,使用Eloquent
$user-> accounts()-> where($primaryKey, $id);
不知怎的,这两者都会产生错误(Eloquent bug?)
$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"函数更优雅的解决方案?
如果这是您最常用的查询之一,为什么不缓存它呢?
$user->accounts()->where($primaryKey, '=', $id)->remember(60)->get();
上述查询失败是因为在两个表中都有一个名称相同的列
where 'users_accounts'.'u_id' = 1 and 'a_id' = 1