我实际上是在为每个帐户使用子域的单个域下构建一个多站点站点。每个帐户都有一组唯一的用户名,但并非在所有站点中都是唯一的。因此,帐户 1 上可能有一个“汤姆”,帐户 2 上可能有一个“汤姆”,但任何一个帐户上都没有 2 个汤姆。
我的用户表有一列指定 account_id,我的 Controller 有子域。因此,在查询用户时,如何确保用户 account_id
与帐户 id
匹配,其中帐户 id = users.account_id
和 accounts.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/