我是Laravel的初学者。我在项目中使用Laravel 5.8。
我有此代码:
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
$table->boolean('enable')->default(0);
$table->string('name', 120)->nullable();
$table->string('surname', 120)->nullable();
$table->string('email', 120)->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->bigInteger('counter')->default(0);
$table->string('url_address', 160);
$table->string('account_paid_for', 12)->nullable();
$table->string('premium_for', 12)->nullable();
$table->string('hits', 12)->nullable();
$table->rememberToken();
$table->timestamps();
$table->engine = "InnoDB";
});
public function getUserList(string $query, string $sortColumn, string $sortMethod)
{
if ($query != "") {
return User::ofRoleType(['user', 'userPremium', 'userCompany', 'userSponsor', 'userGuest'])
->where(function ($q) use ($query, $sortColumn, $sortMethod) {
$q->where('email', 'LIKE', '%' . $query . '%')
->orWhere('id', 'LIKE', '%' . $query . '%')
->orWhere('name', 'LIKE', '%' . $query . '%')
->orWhere('surname', 'LIKE', '%' . $query . '%')
->orderBy($sortColumn, $sortMethod);
})->paginate(2);
} else {
return User::ofRoleType(['user', 'userPremium', 'userCompany', 'userSponsor', 'userGuest'])->paginate(2);
}
}
和用户模型:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
use cms\Presenters\UserPresenter;
public static $roles = [];
protected $fillable = ['name', 'surname', 'email', 'email_verified_at', 'password', ];
protected $hidden = [
'password', 'remember_token',
];
public function roles()
{
return $this->belongsToMany('App\Role');
}
public function mainRole()
{
return $this->hasOne('App\Role');
}
public function hasRole(array $roles)
{
foreach ($roles as $role) {
if (isset(self::$roles[$role])) {
if (self::$roles[$role]) return true;
} else {
self::$roles[$role] = $this->roles()->where('name', $role)->exists();
if (self::$roles[$role]) return true;
}
}
return false;
}
}
我需要按以下顺序显示用户列表:
首先,拥有高级帐户(即日期比今天大的premium_for字段)的用户,
然后在“点击数”字段中拥有最大数量的用户
其他用户
您该怎么做?有人知道如何自定义这种getUserList函数吗?
答案 0 :(得分:4)
我对Laravel的经验很了解,但我认为您是在要求:
->orderBy(DB::raw('IF(premium_for > CURDATE(), 0, 1)'))
->orderBy('hits', 'DESC');
(未经测试)表示要声明:
说明DB::raw()
:https://laraveldaily.com/select-with-dbraw-make-your-database-work/
我还将建议您WS_CONCAT()
的WHERE列,并且仅进行一次LIKE比较。像这样:'Where like' clause using the concatenated value of 2 columns with eloquent