Laravel - 扩展与 orderBy 的关系无法正常工作
Laravel - Extend relationship with orderBy not working properly
我有这个代码:
$query = $platform->challenges();
// return response()->json($query);
$challenges = $query->orderBy('start_date', 'DESC')->get();
return response()->json($challenges);
如您所见,我得到了挑战关系查询生成器,我正在尝试按日期对结果进行排序。如果我取消注释第二行,我会得到 2 个项目数组。但是如果我将 orderBy 添加到构建器中,我只会得到 1 个项目数组。
有什么我遗漏的吗?
编辑
型号代码:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
class Platform extends Model
{
use Cachable;
protected $fillable = ['name', 'connection_key', 'code', 'enabled'];
public function brands()
{
return $this->hasMany('App\Models\Brand');
}
public function challenges()
{
return $this->hasMany('App\Models\Challenge');
}
}
也许是可缓存的特性导致了这里的不良行为?
试试这个(使用获取的集合):
$challenges = $platform->challenges->sortByDesc('start_date');
return response()->json($challenges);
或者这个(使用查询生成器):
$platform->disableCache();
$challenges = $platform->challenges()->orderBy('start_date')->get();
来自文档:
特定型号的手动冲洗
您可以使用以下 artisan 命令刷新特定模型的缓存:
php artisan modelCache:clear --model=App\Model
这在手动更新数据库时会派上用场。您也可以在从 Laravel 应用程序之外的来源更新数据库后触发此操作。
试试这个..
$query = $platform->challenges();
$challenges = $query->orderBy('start_date', 'DESC')->get();
return json_encode($challenges);
您是否有一个名为 "start_date" 的专栏,如果没有,为什么不这样做呢
$challenges = $query->orderBy('created_at', 'DESC')->get();
因为您已经有了 created_at 列
我有这个代码:
$query = $platform->challenges();
// return response()->json($query);
$challenges = $query->orderBy('start_date', 'DESC')->get();
return response()->json($challenges);
如您所见,我得到了挑战关系查询生成器,我正在尝试按日期对结果进行排序。如果我取消注释第二行,我会得到 2 个项目数组。但是如果我将 orderBy 添加到构建器中,我只会得到 1 个项目数组。
有什么我遗漏的吗?
编辑
型号代码:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use GeneaLabs\LaravelModelCaching\Traits\Cachable;
class Platform extends Model
{
use Cachable;
protected $fillable = ['name', 'connection_key', 'code', 'enabled'];
public function brands()
{
return $this->hasMany('App\Models\Brand');
}
public function challenges()
{
return $this->hasMany('App\Models\Challenge');
}
}
也许是可缓存的特性导致了这里的不良行为?
试试这个(使用获取的集合):
$challenges = $platform->challenges->sortByDesc('start_date');
return response()->json($challenges);
或者这个(使用查询生成器):
$platform->disableCache();
$challenges = $platform->challenges()->orderBy('start_date')->get();
来自文档:
特定型号的手动冲洗
您可以使用以下 artisan 命令刷新特定模型的缓存:
php artisan modelCache:clear --model=App\Model
这在手动更新数据库时会派上用场。您也可以在从 Laravel 应用程序之外的来源更新数据库后触发此操作。
试试这个..
$query = $platform->challenges();
$challenges = $query->orderBy('start_date', 'DESC')->get();
return json_encode($challenges);
您是否有一个名为 "start_date" 的专栏,如果没有,为什么不这样做呢
$challenges = $query->orderBy('created_at', 'DESC')->get();
因为您已经有了 created_at 列