【问题标题】:What's Laravel's Eloquent search on relation lightest query?Laravel 对关系最轻查询的 Eloquent 搜索是什么?
【发布时间】:2014-11-23 13:47:54
【问题描述】:

在经典的 Rest API 方法中,我的应用程序需要检查用户是否与某个帐户相关。我们可以对多个帐户执行操作,因此查询会针对每个请求执行。 因为这是我们最常调用的查询,所以它的轻便性对我的安心很重要。

当前查询,使用 Eloquent

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

不知何故,这些都会产生错误(Eloquent 错误?)

$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”函数更优雅的解决方案?

【问题讨论】:

    标签: php mysql laravel eloquent relationship


    【解决方案1】:

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

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

    上述查询失败,因为您在两个表中都有同名的列

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

    【讨论】:

    • 缓存确实是下一步,为提醒喝彩。关于查询,该查询是由 Eloquent 生成的,我确实知道它在哪里失败,但我确实质疑为什么 Eloquent 会生成失败的查​​询。不过,我必须纠正你的最后一句话;允许在哪里(列,值):laravel.com/docs/4.2/queries
    • 是的,你是对的,我总是使用这个参数的显式声明,因为它看起来更清晰。
    • 您介意更新答案的语法部分吗?只是为了不混淆其他读者。
    猜你喜欢
    • 2013-10-03
    • 2017-07-19
    • 2013-06-19
    • 2021-04-10
    • 1970-01-01
    • 2021-09-25
    • 2015-01-21
    • 2017-01-14
    • 1970-01-01
    相关资源
    最近更新 更多