【问题标题】:I cant retrieve id from user in the database我无法从数据库中的用户检索 id
【发布时间】:2022-01-02 16:51:14
【问题描述】:

当我在我的用户模型中使用此代码时

public function get_user_by_email($email)   {
        $data = $this->where('email', $email);
        return $data->id;
    }

我收到此错误

Property [id] does not exist on the Eloquent builder instance.

  at vendor/laravel/framework/src/Illuminate/Database/Eloquent/Builder.php:1602
    1598▕         if ($key === 'orWhere') {
    1599▕             return new HigherOrderBuilderProxy($this, $key);
    1600▕         }
    1601▕ 
  ➜ 1602▕         throw new Exception("Property [{$key}] does not exist on the Eloquent builder instance.");
    1603▕     }
    1604▕ 
    1605▕     /**
    1606▕      * Dynamically handle calls into the query instance.

  1   app/Models/User.php:64
      Illuminate\Database\Eloquent\Builder::__get()

  2   app/Models/invite.php:21
      App\Models\User::get_user_by_email()

请帮忙 该代码应该可以工作,并且我已经用虚拟用户填充了我的数据库。为什么我不能从用户模型中获取我的用户 ID。我为此使用了jetstream

【问题讨论】:

    标签: php laravel eloquent model


    【解决方案1】:

    您需要在Eloquent Builder 上使用first() 以返回Model,然后才能访问其属性。

    $data = $this->where('email', $email)->first();
    return $data->id;
    

    【讨论】:

      【解决方案2】:

      你可以这样试试。

      $data = Model::where('email', $email)->pluck('id');
      

      【讨论】:

        猜你喜欢
        • 2023-03-12
        • 1970-01-01
        • 2012-10-07
        • 2018-02-10
        • 1970-01-01
        • 2015-12-14
        • 1970-01-01
        • 2020-09-07
        • 2019-07-17
        相关资源
        最近更新 更多