dingo 使用 include 关联查询时如何排序

  • 背景是我想在查询商户的时候,一起查出来商户的最近几篇文章。现在文章可以查出,限制文章的返回数量可以。但是当我改变排序的时候会报错(具体报错请看代码块)。

还请各位告知改如果给关联的查询增加约束呢?或许有没有文档让我康康

  • 其实按照文档的写法get()方法也不行 文档链接在此
    补充一下我使用mongodb作为数据库,并安装了jenssegers/laravel-mongodb。
    刚刚想到可能是因为这个原因导致的,决定尝试用mysql试一下。

文档写法:
code

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
        ]);
    }
《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!