Invalid text representation 7 error invalid input syntax for type bigint

Hello all, Problem/Motivation Drupal Version: 9.3.6 PHP Version: 8.1.3 Database: PostgreSQL Database Version: 13.6 Development Environment: Docker 4 Drupal I'm trying to create a view, using fields, one relationship with entity reference field between 2 content types and a contextual filter for content ID. When I try to provide the default value by content ID from URL, it works. Unfortunately, I have to provide default value as "raw value from URL" type.

Hello all,

Problem/Motivation

Drupal Version: 9.3.6
PHP Version: 8.1.3
Database: PostgreSQL
Database Version: 13.6
Development Environment: Docker 4 Drupal

I’m trying to create a view, using fields, one relationship with entity reference field between 2 content types and a contextual filter for content ID. When I try to provide the default value by content ID from URL, it works. Unfortunately, I have to provide default value as «raw value from URL» type. When I try to do it, I get the error message which I paste below:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: "structure" LINE 6: ... ((field_measuring_stations_node_field_data.nid = 'structure... ^: SELECT "node_field_data"."langcode" AS "node_field_data_langcode", "field_measuring_stations_node_field_data"."langcode" AS "field_measuring_stations_node_field_data_langcode", "node_field_data"."created" AS "node_field_data_created", "node_field_data"."nid" AS "nid", "field_measuring_stations_node_field_data"."nid" AS "field_measuring_stations_node_field_data_nid" FROM "node_field_data" "node_field_data" LEFT JOIN "node__field_measuring_stations" "node__field_measuring_stations" ON node_field_data.nid = node__field_measuring_stations.field_measuring_stations_target_id AND node__field_measuring_stations.deleted = :views_join_condition_0 LEFT JOIN "node_field_data" "field_measuring_stations_node_field_data" ON node__field_measuring_stations.entity_id = field_measuring_stations_node_field_data.nid WHERE ((field_measuring_stations_node_field_data.nid = :node_field_data_nid)) AND ("node_field_data"."type" IN (:db_condition_placeholder_1)) ORDER BY "node_field_data_created" DESC NULLS LAST LIMIT 5 OFFSET 0; Array ( [:node_field_data_nid] => structure [:db_condition_placeholder_1] => station [:views_join_condition_0] => 0 )

Steps to reproduce

The way to reproduce the error is:
— Install Drupal 9.3.6 with PHP 8.1.3 and PostgreSQL 13.6 (I’m going to paste docker-compose.yml and .env content as comments, if someone would like to use them).
— Create 2 different content types with entity reference one to another.
— Create a view with contextual filter, providing default value as «raw value from URL» type.

Proposed resolution

I’ve found this issue, while searching a solution. It could be helpful for debugging.

Best,
Orkut

Tag1 supports the Drupal Project.Tag1 logo

im trying figure out with this problem, already search on every website getting same error, not work at all,.,

here is my simple code hope u guys understand

migration diagnosa

public function up()
{
    Schema::create('diagnosas', function (Blueprint $table) {
        $table->id();
        $table->foreignId('user_id')->constrained();
        $table->double('hasil_nilai');
        $table->date('diagnosa_date');
        $table->timestamps();
    });
}

migration diagnosa_gejala

public function up()
{
    Schema::create('diagnosa_gejalas', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('diagnosa_gejala_id');
    $table->foreign('diagnosa_gejala_id')->references('id')->on('diagnosas')
        ->onDelete('cascade');
        $table->unsignedBigInteger('gejala_id');
        $table->foreign('gejala_id')->references('id')->on('gejalas');
        $table->timestamps();
    });
}

migration dianosa_kerusakan

public function up()
{
    Schema::create('diagnosa_kerusakans', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('diagnosa_kerusakan_id');
        $table->foreign('diagnosa_kerusakan_id')->references('id')->on('diagnosas')
        ->onDelete('cascade');
        $table->unsignedBigInteger('kerusakan_id');
        $table->foreign('kerusakan_id')->references('id')->on('kerusakans');
        $table->timestamps();
    });
}

model diagnosa

public function user_id() {
    return $this->belongsTo(User::class, 'user_id');
}
public function diagnosaGejala()
{
    return $this->hasMany(DiagnosaGejala::class);
}
public function diagnosaKerusakan()
{
    return $this->hasMany(DiagnosaKerusakan::class);
}

model diagnosa gejala

public function diagnosa_gejala_id() {
    return $this->belongsTo(Diagnosa::class, 'diagnosa_gejala_id');
}
public function gejala_id() {
    return $this->belongsTo(Gejala::class, 'gejala_id');
}

}

model diagnosa kerusakan

public function diagnosa_kerusakan_id() {
    return $this->belongsTo(Diagnosa::class, 'diagnosa_kerusakan_id');
}
public function kerusakan_id() {
    return $this->belongsTo(Kerusakan::class, 'kerusakan_id');
}

here is little code controller post/save to database diagnosa, diagnosa_gejala, and diagnosa_kerusakan

$kerusakan = Kerusakan::where('kode_kerusakan', $getCode)->select('id')->get();
                $authUser = Auth::user()->id;
                $diagnosa = new Diagnosa;
                $diagnosa->user_id = $authUser;
                $diagnosa->hasil_nilai = $getValue * 100;
                $diagnosa->diagnosa_date = date('Y-m-d');
                $diagnosa->save();
                $diagnosaGejalaBody = [];
                foreach ($gejala as $key => $result) {
                    $diagnosaGejalaBody[$key]['diagnosa_gejala_id'] = $diagnosa->id;
                    $diagnosaGejalaBody[$key]['gejala_id'] = $result;
                }
                DiagnosaGejala::insert($diagnosaGejalaBody);
                $diagnosaKerusakanBody = [];
                foreach ($kerusakan as $key => $result) {
                    $diagnosaKerusakanBody[$key]['diagnosa_kerusakan_id'] = $diagnosa->id;
                    $diagnosaKerusakanBody[$key]['kerusakan_id'] = $result['id'];
                }
                DiagnosaKerusakan::insert($diagnosaKerusakanBody);
                return redirect('diagnosa-hasil/' . $diagnosa->id);

this is little code, controller trying to get data by parameter $id, for sending to blade with url «diagnosa-hasil/{id}»

$getId = Diagnosa::find($id);
        $diagnosa = Diagnosa::whereIn('diagnosas.id', $getId)
            ->join('diagnosa_gejalas', 'diagnosa_gejala_id', '=', 'diagnosas.id')
            ->join('diagnosa_kerusakans', 'diagnosa_kerusakan_id', '=', 'diagnosas.id')
            ->join('gejalas', 'gejala_id', '=', 'gejalas.id')
            ->join('kerusakans', 'kerusakan_id', '=', 'kerusakans.id')
            ->get()
            ->toArray();

this error from herokuapp

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: "95.64" (SQL: select * from "diagnosas" inner join "diagnosa_gejalas" on "diagnosa_gejala_id" = "diagnosas"."id" inner join "gejalas" on "gejala_id" = "gejalas"."id" inner join "diagnosa_kerusakans" on "diagnosa_kerusakan_id" = "diagnosas"."id" inner join "kerusakans" on "kerusakan_id" = "kerusakans"."id" where "diagnosas"."id" in (1, 1, 95.64, 2021-11-18, 2021-11-18T07:02:43.000000Z, 2021-11-18T07:02:43.000000Z))

on my localhost:8000 is work fine,.,

Евгений Вафиев

Добрый вечер) буду благодарен за помощь)
История такая, все сделал, тесты проходили, завис на дестрое…выловил, что приходт в экшн пустой коммент) долго копался, путем переименовая переменных добился, что удаление проходит) нажимаю проверить, и начинают падать тесты на валидации, даже ДД не дает посмотреть, ломается все сразу при приходе в update…
Текст ошибки:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type bigint: "[]" (SQL: select * from "article_comments" where "id" = [] limit 1)

Ревью

Мозги кипят, не пойму, что делаю не так) буду признателен за помощь решения вопроса с этой ошибкой, а так же пояснением того, как имена аргументов в методах влияют на то, что Коммент приходил пустым)

ЗЫ: вижу, что теперь в апдейт экшн приходит пустой коммент

ЗЫЗЫ: если переименовать $articleComment в $comment, то возникает ошибка с БД, следовательно должно быть $articleComment, значит вопрос сужается и остается одна проблема, почему эта переменная пустая)

Евгений Вафиев

Вообщем проблема была в том, что с формы статьи шла переменная comment, а экшн edit принимал $articleComment. То есть там уже comment был пустой, помогло переименование аргумента экшена…Вывод, по ходу нао следить за именнованием переменных ф формах, которые направляют на эушн, если не прав, поправьте) Теперь все работает как надо, но тесты по прежнему не проходят, в Web доступе все работает как я ожидаю, но, при этом, висит так же ошибка 419 статус при ожидании 302

Ревью


1

Евгений Вафиев

Вопрос снят, все решилось сбросом упражнения и копипастом старого содержимого…
хотелось бы узнать все таки с чем все связано)


0

Andy Groza

Евгений, простите, я забыл ответить:( но лучше поздно, чем никогда! Давайте разберемся!

Насколько я понимаю из ошибки, у вас в $articleComment приходит пустой массив, а ведь такая запись: public function destroy(Article $article, ArticleComment $comment) запускает механизм биндинга и лара под капотом выбирает стетьи и комменты по айдишникам.

И я почему-то не увидел кнопки, которая бы удалялала, почему?


0

#laravel #api

Вопрос:

У меня есть проект в Laravel 7, и он сработал. Но по некоторым причинам я хочу провести рефакторинг на Laravel 8. Другие в порядке, но у этого маршрута есть проблема.

Вот мой код маршрута в L7 (сработал) и L8 (ошибка): Маршрут api.php:

 L7:
Route::get('/coa/find', [SettingCoaController::Class, 'findCoa']);

L8:
Route::get('coa/find', 'SettingCoaController@findCoa');
 

И это мой контроллер (тот же код):

 namespace AppHttpControllersSetting;

use AppHttpControllersController;
use IlluminateHttpRequest;
use DB;
use IlluminateSupportFacadesValidator;
use AppCoa;

class CoaController extends Controller
{
    public function findCoa(Request $request)
    {
        $isi = $request -> isi; 
        $findCoa = Coa::where('coaid', 'ilike', "%" . $isi . "%")
        ->orWhere('deskripsi', 'ilike', "%" . $isi . "%")
        ->paginate(20);
        // $findCoa = DB::table('coa')
        // ->where('coaid', 'ilike', "%" . $isi . "%")
        // ->orWhere('deskripsi', 'ilike', "%" . $isi . "%")
        // ->paginate(20);

        return response()->json($findCoa);
    }
 }
 

Либо я использую БД, либо модель в приложенииCoa, это всегда приводит к этой ошибке:

 IlluminateDatabaseQueryException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type integer: amp;quot;findamp;quot; (SQL: select * from amp;quot;coaamp;quot; where amp;quot;idamp;quot; = find limit 1) in file /Users/yosep/Dropbox/projects/Laravel8/kie-l8/vendor/laravel/framework/src/Illuminate/Database/Connection.php on line 692
 

Я не понял, почему запрос стал:
select * from amp;quot;coaamp;quot; where amp;quot;idamp;quot; = find limit 1 ? Независимо от того, меняю ли я контроллер, это всегда приводит к этой ошибке. Но другие методы (индекс, показать($id), уничтожить) в порядке. Только этот все еще испорчен.

Комментарии:

1. Уже пробовал, но все равно не повезло, сообщение об ошибке все то же самое. Запрос по ошибке не совпадает с контроллером.

Ответ №1:

Я не знаю, как это работает, но я меняю api.php, из этого:

 Route::get('/coa/{id}', [SettingCoaController::Class, 'show']);
Route::get('coa/cari', [SettingCoaController::Class, 'findCoa']);

 

к этому:

 Route::get('coa/cari', [SettingCoaController::Class, 'findCoa']);
Route::get('/coa/{id}', [SettingCoaController::Class, 'show']);
 

И то и другое работает!

Может ли кто-нибудь объяснить, почему show api/метод не смог написать первым и привел к этой ошибке?

Комментарии:

1. При первой настройке маршрута, когда вы звоните /coa/cari , ваш маршрут '/coa/{id}' выбирается первым (в основном говорится «URL , начинающийся с /coa/ , а затем что угодно). Вы также можете ограничить параметр {id} использованием только целых чисел с использованием ограничений регулярных выражений , что должно заставить ваши маршруты работать так же, как в вашей первой настройке

Ответ №2:

Первое, что было изменено в привязке контроллера маршрута Laravel 8, чтобы ваш маршрут работал

Маршрут::get(«coa/найти», «НастройкаCoaController@findCoa»);

Вам следует обновить свой «RouteServiceProvider.php» найдите «защищенное пространство имен $ = » ПриложениеHttpКонтроллеры»; » или просто добавьте эту строку, это сработает!

320 votes

1 answers

Get the solution ↓↓↓

Morning guys,
I have two database that are linked, the tables areUser andTheme, have in mind im not that familliar with php and symfony framework.
a Theme is linked to a User :

/src/Entity/Theme.php
/**
     * @ORMManyToOne(targetEntity="AppEntityUser", inversedBy="published")
     * @ORMJoinColumn(nullable=false)
     */
   private $user; 

I’m trying to setup a function that would display all the Theme written by this User based of his lastname, from what i understood@ORMManyToOne(targetEntity="AppEntityUser", inversedBy="published") makes sure my theme isnt only linked by theuser_id but the user entity.

In myThemeController.php my function is set up this way :

/**
     * @Route("/theme/show/{lastname}", name="theme_created_by")
     * [email protected] User $ThemeByUser
     */
    public function userThemes(User $ThemeByUser){
        $html =  $this->twig->render('theme/index.html.twig', [
            'themes' => $this->themeRepository->findBy(
                ['User' => $ThemeByUser], ['created_at' => 'DESC']),
        ]);
        return new Response($html);
    }

It seems like the query made by Doctrine isn’t going thru i get this error :

An exception occurred while executing 'SELECT t0.id AS id_1, t0.name AS name_2, t0.created_at AS created_at_3, t0.updated_at AS updated_at_4, t0.user_id AS user_id_5 FROM theme t0 WHERE t0.id = ?' with params ["Roland"]:

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for type integer: "Roland"

Which mean Doctrine is expecting a int as a parameter but it is receiving a string. While reading the documentation it seems like the parameters are converted to match anything in the data. Maybe im dont fully understand how it works, just need a little guidance.
thank you

2021-11-17

Write your answer


969

votes

Answer

Solution:

Dont know how and why but in my twig file that rendering the function :

<p class="media-body pb-3 mb-0  small lh-125 border-bottom border-gray">
        <strong class="text-gray-dark">Autheur : </strong>
        <a href="{{ path('theme_created_by', {'lastname': theme.user.lastname}) }}">
             {{ theme.user.lastname }}
        </a>
        <br/>
        <a href="{{ path( 'theme_show', {'id' : theme.id} ) }}">
            <strong>{{ theme.name }}</strong><br/>
        </a>

i replace that path line with :

<a href="{{ path('theme_created_by', {'username': theme.user.username}) }}">
             {{ theme.user.lastname }}
        </a>

changed the paramaters passed in my route too : withusername@Route("/themes/by/{username}", name="theme_created_by")
now it works..


Share solution ↓

Additional Information:

Date the issue was resolved:

2021-11-17

Link To Source

Link To Answer
People are also looking for solutions of the problem: zsh: command not found: php

Didn’t find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.


Similar questions

Find the answer in similar questions on our website.

Понравилась статья? Поделить с друзьями:
  • Invalid syntax python ошибка else
  • Invalid syntax python ошибка elif
  • Invalid syntax python perhaps you forgot a comma ошибка
  • Invalid stored block lengths ошибка
  • Invalid start mode archive offset tlauncher ошибка