duanchu3376 2015-09-25 20:14
浏览 41
已采纳

在Auth,Laravel 5.1上更改SQL查询

When logging in, the query fails, because "email" is not on "usuario", it's in "persona"

Unknown column 'email' in 'where clause' (SQL: select * from `usuario` where `email` = admin@localhost limit 1)

It's not a solution to change the database model, as not all "persona" are "usuario", but all "usuario" are "persona".

Tried to set the relationships:

class Persona extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
{....}
public function usuario()
{
    return $this->hasOne('App\Usuario');
}
//----------------------------------------------------//
class Usuario extends Model implements AuthenticatableContract,
                                AuthorizableContract,
                                CanResetPasswordContract
{
{....}
public function persona()
{
    return $this->hasOne('App\Persona');
}

Both tables have the same key.

But the query doesn't change, I though maybe Laravel could make an "INNER JOIN" somewhere, don't know if Laravel can do that automatically, so I tried to change the query but don't know exactly where is located.

I thought in a solution like this, but it looks too easy, don't know if would be a good way =/


  • Get EMAIL and PASSWD from post
  • Get the ID, EMAIL and PASSWD from the BD with the SQL
  • If [EMAIL and PASSWD match] Auth::loginUsingId(ID); [ELSE] Return with the errors.

As far as I know, the Auth::loginUsingId(ID); acts like a successful Auth::attempt()... but with this solution I'll need to know how to implement later Throttles and the "remember" option separately... all thoughts are welcome :D

  • 写回答

1条回答 默认 最新

  • duankang8114 2015-09-30 00:42
    关注

    I found a solution: changed postLogin() but inside AuthController, so I can preserve the Throttles and Remember features, and the core still unchanged, here's the code if I can help others:

    //------------------------------------
    // Auth\AuthController.php
    //------------------------------------
    
    protected function postLogin(Request $request)
    {
        $this->validate($request, [
            $this->loginUsername() => 'required', 'password' => 'required',
        ]);
    
        // If the class is using the ThrottlesLogins trait, we can automatically throttle
        // the login attempts for this application. We'll key this by the username and
        // the IP address of the client making these requests into this application.
        $throttles = $this->isUsingThrottlesLoginsTrait();
    
        if ($throttles && $this->hasTooManyLoginAttempts($request)) {
            return $this->sendLockoutResponse($request);
        }
    
        $credentials = $this->getCredentials($request);
    
        //Here's the custom SQL, so you can retrieve a "user" and "pass" from anywhere in the DB
        $usuario = \DB::select('
                SELECT
                    persona.nombre,
                    usuario.password
                FROM
                    persona
                INNER JOIN
                    usuario ON persona.id_persona = usuario.id_persona
                WHERE
                    persona.email = ?
                LIMIT 1', array($credentials['email']));
    
        // Instead of:
        // if (Auth::attempt($credentials, $request->has('remember'))) {
        if ($usuario && Hash::check($credentials['password'], $usuario[0]->password)) {
            Auth::loginUsingId($usuario[0]->id_persona, $request->has('remember'));
    
            // Put any custom data you need for the user/session
            Session::put('nombre', $usuario[0]->nombre);
    
            return $this->handleUserWasAuthenticated($request, $throttles);
        }
    
        // If the login attempt was unsuccessful we will increment the number of attempts
        // to login and redirect the user back to the login form. Of course, when this
        // user surpasses their maximum number of attempts they will get locked out.
        if ($throttles) {
            $this->incrementLoginAttempts($request);
        }
    
        return redirect($this->loginPath())
            ->withInput($request->only($this->loginUsername(), 'remember'))
            ->withErrors([
                $this->loginUsername() => $this->getFailedLoginMessage(),
            ]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line