Итак, я создаю часть программного обеспечения, которая интегрируется с нашим PSA и получает данные с платформы, которую мы используем для создания цифровой вывески для цитат и т. П.
Поскольку планируется интегрировать это сНаш PSA, который в настоящее время создается, мы регистрируем все это в нашем приложении laravel и сохраняем данные, которые проходят через него, в наш текущий PSA.
Я создал черту, которая выполняет поиск, сначала в нашей базе данных, изатем против записи объекта в СРП.Все отлично работает с первоначальным созданием или поиском, но после того, как мы нашли его и сохранили в нашей базе данных, у меня возникли проблемы с построителем запросов, игнорирующим значение, которое я передаю, и вместо этого выполняющим запрос ниже.
SELECT * FROM `accounts` WHERE `AccountName` = ?
Ниже приведен код, который выполняет функцию поиска:
/**
* Performs a double lookup, first in the local DB and then against Autotask
* if nothing is returned from autotask or DB then null will be returned
*
* @param string $entityType The Entity type used in queries in Autotask (eg. Ticket)
* @param string $field The Column name to run the query against (eg. EMailAddress)
* @param string $value The value that will be looked up (eg. test@email.org)
*
* @return self|null
*/
public static function doubleLookup(/*string $entityType, */string $field, string $value, string $op = 'Equals')
{
preg_match('/([^\\\]+$)/', self::class, $output_array);
$entityType = $output_array[0];
$result = self::where($field, $op, $value)->get(); // ngl this is fucking cool. I'm very pleased with this tbh
// dd(self::where($field, $op, "Example Name")->toSql()); // this is what dumps the SQL. Tested with var which is never null and with static value to same result.
if ($result->count()) {
return $result->first();
}
// If we've gotten to this point we can assume that it doesn't exist in our database so we
// we should try and find a reference in Autotask
$client = self::client();
// build out our query using our supplied variables.
$query = new Query($entityType);
$queryField = new QueryField($field);
$queryField->addExpression($op, $value);
$query->addField($queryField);
// Because Autotask is cancer we need to wrap this in a try catch.
// Integrator account often locks by itself and idk why'
// This prevents us getting loads of low level 500 Errors that are imposible to debug
try {
$result = $client->query($query)->queryResult->EntityResults->Entity;
} catch (\Throwable $th) {
return dd($th);
}
// if $result->EntityResults->Entity != truthy (i.e null or false)
if (!$result)
return null;
// because autotask is just straight up cancer it can return either a single entity or an array.
// the array for some unknown reason can be empty which is just seriously dumb.
if (!is_array($result)) {
// we have matched a single result in autotask. This is honestly the best case scenario.
$entity = new self(Arr::except((array) $result, ['UserDefinedFields']));
$entity->AutotaskID = $result->id;
} else {
// we have matched an array of entities in autotask. This is honestly the best case scenario.
$entity = new self(Arr::except((array) $result[0], ['UserDefinedFields']));
$entity->AutotaskID = $result[0]->id;
}
$entity->save();
return $entity;
}
Эта функция вызывается этим методом в контроллере для контекста
public function quotient(Request $request)
{
$bag = json_decode($request->getContent(), true);
$account = Account::doubleLookup('AccountName', $bag['quote_for']['company_name']);
...
Любая помощь будет принята с благодарностью:Я чешу голову и до сих пор не могу найти ответ на этот вопрос.
Заранее спасибо.