How to leave the native ID in Laravel nova field with IndexQuery with ->join()?

Viewed 198

Created HasMany Laravel Nova field, on the related resource added indexQuery where joined another table. But as a result I got another ID and created_at in the result table.

HasMany::make('Changes log', 'logger', \App\Nova\MyResource::class),

In MyResource

/**
     * Get the fields displayed by the resource.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make(),
          ];
    }

public static function indexQuery(NovaRequest $request, $query)
    {
        return $query->leftJoin('model_has_roles', 'logger.user_id', '=', 'model_has_roles.model_id')
                     ->leftJoin('roles', 'roles.id', '=', 'model_has_roles.user_id')
                     ->where('roles.name', 'Admin');
    }

As a result I got the data I needed except of ID and created_at/updated_at, ID is always - 1

1 Answers

Try adding select statement as below

public static function indexQuery(NovaRequest $request, $query)
{
    return $query
        ->select('TableName.*')
        ->leftJoin('model_has_roles', 'logger.user_id', '=', 'model_has_roles.model_id')
        ->leftJoin('roles', 'roles.id', '=', 'model_has_roles.user_id')
        ->where('roles.name', 'Admin');
}
Related