Merklin's avatar

Main element id replaced by the joined element id

I am running this query:

TaskNote::select(['id AS task_note_id', 'task_id', 'added_by ', 'note'])
                ->join('tasks', 'tasks.id', '=', 'task_notes.task_id')
                ->where('tasks.user_id', auth()->id())
                ->orWhere('tasks.created_by', auth()->id())
                ->orWhere('tasks.reviewer_id', auth()->id())
                ->get();

but for some reason, in the result the task_notes.id is replaces by the task.id. I've tried also to set the field like task_notes.id AS task_note_id, but in this case task_note_id is missing from the result and again the task_note.id is replaced by the task.id

This is one of the results:

0 likes
4 replies
RemiM's avatar

The issue comes from your select() statement. When using select(['id AS task_note_id', ...]), Laravel interprets id as task_notes.id, but when you alias it (id AS task_note_id), it may get overridden due to the join(). Here's how to fix it explicitly:

TaskNote::select([
        'task_notes.id AS task_note_id', 
        'task_notes.task_id', 
        'task_notes.added_by', 
        'task_notes.note'
    ])
    ->join('tasks', 'tasks.id', '=', 'task_notes.task_id')
    ->where('tasks.user_id', auth()->id())
    ->orWhere('tasks.created_by', auth()->id())
    ->orWhere('tasks.reviewer_id', auth()->id())
    ->get();

Merklin's avatar

@RemiM I've mentioned that I've tried this approach and the result is the same.

RemiM's avatar

It looks like there's a mismatch between your model and the actual data. Your id appears to be a UUID string, but your TaskNote model defines #primaryKey: "id" with #keyType: "int".

Since the id is not an integer, Eloquent is likely treating it incorrectly. You may need to update your model to ensure it recognizes the id as a string instead of an integer.

Check the official documentation for UUID keys: https://laravel.com/docs/11.x/eloquent#uuid-and-ulid-keys and https://laravel.com/docs/11.x/migrations#column-method-uuid

Please or to participate in this conversation.