繁体   English   中英

在Laravel的Eloquent ORM中加入() - > where()

[英]join()->where() in Laravel's Eloquent ORM

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

我的users表有一个指定account_id的列,我的控制器有子域。 因此,向用户询问的时候,我怎么能保证用户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();

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

我设法通过使用DB :: raw()来使查询工作,但是如果有更好的方法我很好奇。

你有方法whereRaw。

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

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

您可以使用globalScopes: https ://laravel.com/docs/5.3/eloquent#query-scopes

->where(X, Y)将列X与 Y进行比较。

->whereColumn(X, Y)将列X与 Y进行比较。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM