dingo 使用 include 关联查询时如何排序
- 背景是我想在查询商户的时候,一起查出来商户的最近几篇文章。现在文章可以查出,限制文章的返回数量可以。但是当我改变排序的时候会报错(具体报错请看代码块)。
还请各位告知改如果给关联的查询增加约束呢?或许有没有文档让我康康
- 其实按照文档的写法get()方法也不行 文档链接在此
补充一下我使用mongodb作为数据库,并安装了jenssegers/laravel-mongodb。
刚刚想到可能是因为这个原因导致的,决定尝试用mysql试一下。
文档写法:
namespace App\Http\Transformers;
use App\Merchant;
use League\Fractal\ParamBag;
use League\Fractal\TransformerAbstract;
class MerchantTransformer extends TransformerAbstract
{
protected $availableIncludes = [
'news'
];
protected $defaultIncludes = [];
private $validParams = ['limit'];
public function transform(Merchant $merchant)
{
return [
'name' => $merchant->shop_name,
'shop_logo' => $merchant->shop_logo,
'address' => $merchant->address . $merchant->house_number ?? '',
'status' => $merchant->status
];
}
public function includeNews(Merchant $merchant, ParamBag $params = null)
{
list($limit) = $params->get('limit') ?? [6];
//在这里使用take方法可以限制文章的返回数量,使用orderBy方法会返回错误:
//Method Illuminate\\Database\\Eloquent\\Collection::orderBy does not exist.
$news = $merchant->news->take($limit);
$next['next'] = $news->last()->_id ?? null;
return $this->collection($news, new StoreNewsTransformer())->setMeta([
'cursor' => $next
]);
}