[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();
~~~