php - Laravel Eloquent ORM 中的 join()->where()

标签 php mysql laravel orm eloquent

我实际上是在为每个帐户使用子域的单个域下构建一个多站点站点。每个帐户都有一组唯一的用户名,但并非在所有站点中都是唯一的。因此,帐户 1 上可能有一个“汤姆”,帐户 2 上可能有一个“汤姆”,但任何一个帐户上都没有 2 个汤姆。

我的用户表有一列指定 account_id,我的 Controller 有子域。因此,在查询用户时,如何确保用户 account_id 与帐户 id 匹配,其中帐户 id = users.account_idaccounts.subdomain = $subdomain?

这是我正在尝试的:

$user = User::whereUsername($username)
    ->leftJoin('accounts', 'accounts.id', '=', 'users.account_id')
    ->where('accounts.id', '=', 'users.account_id')
    ->where('accounts.subdomain', '=', $subdomain)
    ->firstOrFail();

问题在于它将 users.account_id 作为文字字符串而不是表引用。

其次,关于此设置,是否有更好的方法来解决此问题,以便无论何时我在子域上,它都只会提取相关数据,而我不必重复?

更新: 我设法通过使用 DB::raw() 使查询正常工作,但我很好奇是否有更好的方法。

$user = User::whereUsername($username)
    ->leftJoin('accounts', 'accounts.id', '=', 'users.account_id')
    ->where('accounts.id', '=', DB::raw('users.account_id'))
    ->where('accounts.subdomain', '=', $subdomain)
    ->firstOrFail();

此外,仍然有兴趣收到我的第二个问题的答案。

最佳答案

I managed to get the query working by using DB::raw() but am curious if there is a better way.

您有方法 whereRaw。

$user = User::whereUsername($username)
->leftJoin('accounts', 'accounts.id', '=', 'users.account_id')
->whereRaw('accounts.id = users.account_id')
->where('accounts.subdomain', '=', $subdomain)
->firstOrFail();

Secondly, in relation to this setup, is there a better way to approach this so that anytime I'm on a subdomain it will pull only relevant data without me have to be repetitive?

您可以使用全局范围:https://laravel.com/docs/5.3/eloquent#query-scopes

关于php - Laravel Eloquent ORM 中的 join()->where(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24470301/

相关文章:

php - PJAX 和 Firefox 后退按钮问题

javascript - 使用 Ajax 时,变量应该如何从 JavaScript 传递到 PHP?

javascript - 如何获取动态生成的td属性和内部元素id标签的值,其中tr在js/jquery中具有id

拉拉维尔 4 : ErrorException Undefined variable

php - 变化无常的变革冲突

mysql - 如何使用不同的关键字删除重复值

mysql - 在数据库中,什么时候应该存储派生数据?

php - 每当mysql更新时动态更新json文件

php - 喜欢使用 Laravel 构建表格,并在顶部显示最受欢迎的内容

ruby - 如何将 laravel 数组转换为 ruby​​ 哈希访问