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

时间:2014-06-28 19:43:36

标签: php mysql laravel orm eloquent

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

我的用户表有一个指定account_id的列,我的控制器有子域。因此,在查询用户时,如何确保用户account_id与帐户idid = 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();

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

2 个答案:

答案 0 :(得分:1)

  

我设法通过使用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

答案 1 :(得分:1)

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

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