如何控制在Cake 3.x中为belongsToMany显示分页的字段?

时间:2016-03-11 04:08:23

标签: cakephp pagination cakephp-3.0

情况

使用Cake 3.2.4

我有EventTicketSales

  $this->belongsToMany('Approvings', [
        'className' => 'Contacts',
        'joinTable' => 'event_ticket_sales_approvings',
        'targetForeignKey' => 'contact_id',
        'saveStrategy' => 'replace',
    ]);

因此,当我在EventTicketSales表中进行分页时,我只想显示Approvings中的2个字段,即Approvings.name和Approvings.company。

我尝试了什么

我尝试了以下内容:

$this->paginate["contain"] = ["Approvings"];
$this->paginate['fields'] = [
            'EventTicketSales.id', 'EventTicketSales.event_id', 'EventTicketSales.billing_amount_in_sgd', 
            'EventTicketSales.payment_terms', 'EventTicketSales.invoice_number', 
            'EventTicketSales.due_date',
  'Approvings.id', 'Approvings.name', 'Approvings.company'
        ];

我在非相关模型中收到有关JsonSerialize的错误消息。

  [Exception] Failed calling App\Model\Entity\User::jsonSerialize() #0 /var/virtual/WebApps/corri/vendor/cakephp/cakephp/src/View/JsonView.php(0

我的期望

我期待以下结果:(我以json格式显示)

id: "06f39ba3-9a17-47c6-9374-24b49fb64665",
event_id: 7,
billing_amount_in_sgd: 7680.03,
payment_terms: "45 days",
invoice_number: "9191",
due_date: "2016-03-05T00:00:00+0800",
approvings: [
    {
        id: 63,
        name: "Jaime Jen",

        company: "Apple Company",

        _joinData: {
            contact_id: 63,
            id: 335,
            event_ticket_sale_id: "06f39ba3-9a17-47c6-9374-24b49fb64665",
            created: "2016-01-20T13:43:44+0800",
            modified: "2016-01-20T13:43:44+0800"
        }
    }
]

1 个答案:

答案 0 :(得分:1)

分页器fields选项正在应用于主查询查找器,并且由于belongsToMany分配是通过seaprate查询检索的,因此该选项不会对其产生任何影响。< / p>

相反,您必须相应地配置包含,即使用回调或fields选项。另请注意,在限制hasManybelongsToMany关联时,您还必须选择正确的外键。

$this->paginate['contain'] = [
    'Approvings' => function (\Cake\ORM\Query $query) {
        return $query->select([
            'Approvings.id',
            'Approvings.name',
            'Approvings.company',
            'EventTicketSalesApprovings.event_ticket_sale_id'
        ]);
    }
];

另见