[TOC]
### 创建查询类
~~~
namespace App\Model;
/**
* @method $this | \Hyperf\Database\Query\Builder genderMale()
* @method $this | \Hyperf\Database\Query\Builder type(string $typeVal)
* @method $this | \Hyperf\Database\Query\Builder sex(string $sexVal)
*
*/
trait LinkQuery
{
/**
* Begin querying the model.
*
* @return $this
*/
public static function query()
{
return (new static())->newQuery();
}
/**
* 查询最新用户列表
* @param $query \Hyperf\Database\Query\Builder
*/
public function scopeLastestUsers($query){
$query->where('id', '>', 100);
}
/**
* 类型查询
* @param $query \Hyperf\Database\Query\Builder
* @param $typeVal string
*/
public function scopeType($query, $typeVal){
$query->where('type', $typeVal);
}
/**
* 性别查询
* @param $query \Hyperf\Database\Query\Builder
* @param $typeVal string
*/
public function scopeSex($query, $sexVal){
$query->where('sex', $sexVal);
}
}
~~~
### 模型中使用查询类
> /app/Model/User.php 中use trait
~~~
declare(strict_types=1);
namespace App\Model;
use Hyperf\DbConnection\Model\Model;
/**
* @property $id
* @property $name
* @property $gender
* @property $created_at
* @property $updated_at
*/
class User extends Model
{
// 使用查询类
use LinkQuery;
/**
* The table associated with the model.
*
* @var string
*/
protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['id', 'name', 'gender', 'created_at', 'updated_at'];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = ['id' => 'integer', 'gender' => 'integer'];
}
~~~
### Controller中使用测试
~~~
$result = Link::query()->lastestNews()->get();
$result = Link::query()->type('战略合作伙伴')->get();
~~~