oope's avatar
Level 1

Column 'id' in field list is ambiguous select2 edit mode

Hi, i have a problem to take data from relationship belongstomany, i try take data when i edit post and i have this error this '1052 Column 'id' in field list is ambiguous'.

error:SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in field list is ambiguous

SELECT `id` FROM `tags` INNER JOIN `post_tag` ON `tags`.`id` = `post_tag`.`` WHERE `post_tag`.`` = 6

code:

             
            @foreach ($tagSelect  as $tagSe)
            <option value="{{$tagSe->id}}" {{($post->tags()->pluck('id')->contains($tagSe->id)) ? 'selected' : ''}}>
            {{$tagSe->name }}
            </option>
            @endforeach```
0 likes
2 replies
Snapey's avatar

not sure about the error, but what you are doing will give an n+1 issue as you query the database on every loop through the foreach.

In the controller, load the post tags and then just do the compare in the loop

            @foreach ($tagSelect  as $tagSe)
            <option value="{{$tagSe->id}}" {{ $post->tags->contains('id', $tagSe->id) ? 'selected' : ''}}>
            {{$tagSe->name }}
            </option>
            @endforeach```

1 like
rodrigo.pedra's avatar

The ambiguity is solved by speciying the table name from where you want to retrieve the id field. Probably your pivot table (post_tag) also has a column named id, so SQL does not know which id column to retrieve.

->pluck('tags.id')

But please consider, and read carefully @snapey answer. It is a much better approach.

In your current code you are executing a different query to the database for each $tagSelect item. If this array has 100 items you are going to execute 100 queries, which will be very slow.

Using @snapey suggestion you would execute just one query instead.

On Laravel docs there is a nice explanation of the N+1 query problem referred in @snapey answer:

reference: https://laravel.com/docs/9.x/eloquent-relationships#eager-loading

Please or to participate in this conversation.