这样的事情怎么样:
- 从表中获取所有内容。
- 使用收集的结果得到所有不为空的级别,然后对它们进行排序。
- 使用收集的结果获取所有空级别,然后对其进行排序。
- 合并2个排序的集合结果并提取名称。
// 1. Get all from the table.
$warehouses = Wharehouse::all();
// 2. Using the collected results get all without null levels then sort them.
$warehousesWithLevels = $warehouses->where('level', '!=', null)
->sortBy('level');
// 3. Using the collected results get all with null levels then sort them.
$warehousesWithoutLevels = $warehouses->where('level', null)
->sortByDesc('id');
// 4. Merge the 2 sorted collection results and pluck the name.
$warehousesSorted = $warehousesWithLevels->merge($warehousesWithoutLevels)->pluck('name');
dd($warehousesSorted);
或者配合我在模型中创建的Scope你可以使用:
Wharehouse::allSortedMyWay();
上面有一个数据库查询,然后处理收集的结果。
您可以修改最适合您需要的任何键的排序。
测试结果如下:
Collection {#268 ▼
#items: array:5 [▼
0 => "hiroshima"
1 => "osaka"
2 => "nagoya"
3 => "sapporo"
4 => "tokyo"
]
}
我使用的型号:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Wharehouse extends Model
{
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'warehouses';
/**
* Indicates if the model should be timestamped.
*
* @var bool
*/
public $timestamps = false;
/**
* The attributes that are not mass assignable.
*
* @var array
*/
protected $guarded = [
'id',
];
/**
* Fillable fields for a Profile.
*
* @var array
*/
protected $fillable = [
'name',
'level',
];
}
/**
* Return all warehousts sorted my way - Quick but not a true query scope.
*
* @return collection
*/
public function scopeAllSortedMyWay()
{
$warehouses = Wharehouse::all();
$warehousesWithLevels = $warehouses->where('level', '!=', null)
->sortBy('level');
$warehousesWithoutLevels = $warehouses->where('level', null)
->sortByDesc('id');
return $warehousesWithLevels->merge($warehousesWithoutLevels)->pluck('name');
}
我使用的播种机:
<?php
use App\Wharehouse;
use Illuminate\Database\Seeder;
class WharehouseTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
$items = [
[
'name' => 'osaka',
'level' => 3,
],
[
'name' => 'tokyo',
'level' => null,
],
[
'name' => 'sapporo',
'level' => null,
],
[
'name' => 'nagoya',
'level' => 4,
],
[
'name' => 'hiroshima',
'level' => 1,
],
];
foreach ($items as $item) {
$newItem = Wharehouse::where('name', '=', $item['name'])->first();
if ($newItem === null) {
$newItem = Wharehouse::create([
'name' => $item['name'],
'level' => $item['level'],
]);
}
}
}
}
我使用的迁移:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateWarehouseTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('warehouses', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name')->unique();
$table->integer('level')->nullable();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('warehouses');
}
}