我有 3 个集合:“客户”、“经销商”和“订单”。 客户与经销商之间存在多对一的关系。 经销商与客户之间是一对多的关系。 订单与客户之间存在多对一的关系。
我想使用之前配置的多对一关系,根据所选客户自动设置orders.reseller 字段。
$payload 对象仅包含“orders”列,因此我看不到“customer.reseller”,只能看到“customer”。
https://docs.directus.io/extensions/hooks.html#filter-hooks
Dot Notation get() and has() method can use dot-notation to access child elements. eg: get('data.email').
Payload Object Payload object is Arrayable which means you can interact with the data as an array $payload['data']['email], but you can't do \Directus\Util\ArrayUtils::get($payload, 'data.email').
当尝试使用 \Directus\Util\ArrayUtils::get()
时,我没有得到任何返回结果,但 $payload->get()
的工作原理如下预期的。在下面的示例中,我只是将返回的数组设置为订单项中的文本字段(“out”)以进行测试。
'filters' => [
'item.create.orders:before' => function (\Directus\Hook\Payload $payload) {
$data = $payload->getData();
//$data = $payload->get('customer');
//$data = \Directus\Util\ArrayUtils::get($payload,'customer');
$out = json_encode($data);
$payload->set('out',$out);
return $payload;
}
我希望 ArrayUtils 中的 get 函数允许我将其作为数组进行交互,并根据所选的“客户”从“客户”表中检索“经销商”列。
有效负载对象仅返回一个数组,例如:{"order_number":"1234","customer":"15"}
“客户”字段应与“客户”表中的“id”(行)匹配,我想查看该表的“经销商”列值。
最佳答案
我的解决方案是使用 ZendDB 查询而不是 get 函数。
https://docs.directus.io/api/data.html#zend-db-tablegateway
'item.create.orders:before' => function (\Directus\Hook\Payload $payload) {
$customer_id = $payload->get('customer'); //get customer_id from 'order' item
$container = \Directus\Application\Application::getInstance()->getContainer();
$dbConnection = $container->get('database'); // connect to database
$table = new \Zend\Db\TableGateway\TableGateway('customers', $dbConnection); // connect to table
$results = $table->select(['id' => $customer_id]); // select row with 'customer_id'
$customer = $results->current(); // get array of current 'customer' row
$reseller = $customer->reseller; // get 'reseller' column value from row
$payload->set('reseller',$reseller); //Update Payload
return $payload;
}
关于php - 使用相关字段更新项目的示例过滤器 Hook ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55347047/