为什么Laravel 5.6 / Eloquent不同意它自己的数据库连接?

时间:2018-04-25 23:29:50

标签: php laravel eloquent laravel-5.6

我的应用程序在生产环境中展示了这种奇怪的行为,没有其他地方(在实际界面和修补程序中都发生):

>>> $db = DB::connection();
=> Illuminate\Database\MySqlConnection {#832}
>>> \App\User::resolveConnection()->select('select * from users');
=> [
     {#838
       +"id": 2,
       +"deleted_at": "2018-04-10 20:47:07",
       ...perfectly normal data
     },
     {#848
       +"id": 3,
       +"deleted_at": "2018-04-10 20:47:07",
       ...perfectly normal data
     },
   ]
>>> \App\User::resolveConnection()->select('select * from users');
=> [
     {#846
       +"id": 2,
       ...perfectly normal data
     },
     {#839
       +"id": 3,
       ...perfectly normal data
     },
   ]
>>> \App\User::all();
=> Illuminate\Database\Eloquent\Collection {#861
     all: [],
   }

User类很简单:

namespace App;

use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Spatie\Permission\Traits\HasRoles;
use Laravel\Cashier\Billable;

class User extends Authenticatable
{
    use SoftDeletes;
    use Billable;
    use HasApiTokens, Notifiable, HasRoles;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'name', 'email', 'password', 'status'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];

    public function organization()
    {
        return $this->hasOne(Organization::class);
    }
}

1 个答案:

答案 0 :(得分:2)

我的第一个想法是你在User模型上使用软删除。因此,您的所有用户都被软删除了吗?

Eloquent会自动应用相关的软删除查询范围来过滤已删除的模型,而标准数据库查询则不会。

等效的DB查询将是:

SELECT * FROM users WHERE deleted_at IS NULL